Skip to content

Instantly share code, notes, and snippets.

@rotexdegba
Last active September 9, 2022 01:12
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 rotexdegba/9751711 to your computer and use it in GitHub Desktop.
Save rotexdegba/9751711 to your computer and use it in GitHub Desktop.
Alternative implementation of in_array using either isset or array_key_exists. This approach requires restructuring the original array.
<?php
//This isset optimization is not suitable for arrays that contains null values.
/*
$a = array('a' => null);
isset($a['a']); // Will be FALSE
array_key_exists('a', $a); // Will be TRUE
*/
$total = 10000;
$paragraph = 'this is a sentence. Crud! $$$$!';
$words = explode(' ', $paragraph);
// Create a bunch of letter entries
$sequence = [];
for ($j = 0; $j < 10000; $j++) {
$sequence[] = 'a' . $j;
}
$s = microtime(true);
for ($j = 0; $j < $total; $j++) {
foreach ($words as $word) {
in_array(strtolower($word), $sequence);
}
}
echo "in_array: " . (microtime(true) - $s) . "\n";
// Convert the array to a hash
$hash = array_fill_keys($sequence, true);
$s = microtime(true);
for ($j = 0; $j < $total; $j++) {
foreach ($words as $word) {
isset($hash[strtolower($word)]);
}
}
echo "isset: " . (microtime(true) - $s) . "\n";
$s = microtime(true);
for ($j = 0; $j < $total; $j++) {
foreach ($words as $word) {
array_key_exists(strtolower($word), $hash);
}
}
echo "array_key_exists: " . (microtime(true) - $s) . "\n";
@parijke
Copy link

parijke commented May 4, 2022

Since you have two arrays, you could use the array_intersect instead of a foreach loop?

@rotexdegba
Copy link
Author

Since you have two arrays, you could use the array_intersect instead of a foreach loop?

Thanks

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