Skip to content

Instantly share code, notes, and snippets.

@Maks3w
Created July 12, 2012 11:51
Show Gist options
  • Save Maks3w/3097685 to your computer and use it in GitHub Desktop.
Save Maks3w/3097685 to your computer and use it in GitHub Desktop.
in_array vs foreach
<?php
$value = 'A';
$haystack = array('test', 0, 'A');
$strict = false;
$s = microtime(true);
in_array($value, $haystack, $strict);
$e = microtime(true);
echo ' ' . ($e - $s) . PHP_EOL;
$s = microtime(true);
foreach ($haystack as $element) {
if ($strict) {
if ($element === $value) {
$x = true;
}
} elseif ($element == $value) {
$x = true;
}
}
$e = microtime(true);
echo ' ' . ($e - $s) . PHP_EOL;
// 5.9604644775391E-6 //in_array strict=FALSE
// 8.1062316894531E-6 //foreach strict=FALSE
// 5.9604644775391E-6 //in_array strict=TRUE
// 5.9604644775391E-6 //foreach strict=TRUE
// After a bunch of executions the times still beeing equals between the two implementations
@codebard
Copy link

great stuff. just what i was looking for. meaning if we dont use strict there is not much difference in between foreach and in_array

thanks.

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