<?php
function array_key_exists_test( $n )
{
//setup the array
$array = array();
$set_key_count = (int)($n/2);
for( $i = 0; $i < $set_key_count; $i++ ) {
do {
$rand_number = rand( 0, $n-1 );
} while( array_key_exists( $rand_number, $array ) );
$array[$rand_number] = NULL;
}
$test_array = range( 0, $n-1 );
shuffle( $test_array );
$result_array = array();
$start = microtime(true);
foreach( $test_array as $test_number ) {
if( array_key_exists( $test_number, $array ) ) {
$result_array[] = $test_number;
}
}
$stop = microtime(true);
if( count( $result_array ) !== $set_key_count )
throw new Exception( "test failed" );
return ( $stop - $start ) / $n;
}
$n_array = range( 1, 100 );
$n_array = array_map( function( $n ) { return $n * 10000; }, $n_array );
foreach( $n_array as $n ) {
print sprintf( "at n of %d time per call %.10f\n", $n, array_key_exists_test( $n ) );
}
?>