Skip to content

Instantly share code, notes, and snippets.

@cereal-s
Created June 10, 2019 20:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cereal-s/1427a52f88bbedafe3a06a55a671015b to your computer and use it in GitHub Desktop.
Save cereal-s/1427a52f88bbedafe3a06a55a671015b to your computer and use it in GitHub Desktop.
Find value into an array. Comparison between for loop + if/else, in_array(), and array_flip() + for loop + isset().
<?php
function _report($start) {
$total_time = microtime( true ) - $start;
echo PHP_EOL;
echo 'Total time: ' . number_format($total_time, 6);
echo PHP_EOL;
echo PHP_EOL;
}
$a = [];
for ($i = 0; $i < 1000000; $i++) {
$a[] = mt_rand(1, 10000000);
}
$c = $b = $a;
// Randomize
shuffle($b); // random number
shuffle($c); // collection to search
$rnd = $b[0];
$cnt = count($a);
echo 'Size: ' . $cnt;
echo PHP_EOL;
echo 'Random: ' . $rnd;
echo PHP_EOL;
echo PHP_EOL;
// Method 1
$start = microtime( true );
for($i = 0; $i <= $cnt; $i++)
{
if($c[$i] === $rnd)
{
echo 'Method #1';
break;
}
}
_report($start);
// Method 2
$start = microtime( true );
if(in_array($rnd, $c)) {
echo 'Method #2';
}
_report($start);
// Method 3
$start = microtime( true );
$flip = array_flip($c);
for($i = 0; $i <= $cnt; $i++)
{
if(isset($flip[$rnd]))
{
echo 'Method #3';
break;
}
}
_report($start);
@cereal-s
Copy link
Author

Example of output:

> php ./run.php
Size: 1000000
Random: 9386986

Method #1
Total time: 0.010851

Method #2
Total time: 0.001683

Method #3
Total time: 0.081779

Results will vary every time, depends on the position of the value into the array. But method #2 (in_array()) seems the more reliable. While searching I have found some that suggest the usage of array_flip() but then they do not include the function in the benchmark, which in a real-world example it is not correct. The above is just an attempt to emulate a more practical situation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment