Last active
September 26, 2019 10:11
-
-
Save janmyszkier/2974796128aa017aa9d4fd38465bede8 to your computer and use it in GitHub Desktop.
58113854 Quickest way to get the key by value of a multidimensional associative array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$initialArray = []; | |
for ($i = 0; $i < 10000; $i++) { | |
$data[] = [ | |
'Joe Bloggs', | |
rand(0, 99999), | |
'Manager', | |
'Male', | |
12 | |
]; | |
} | |
$data[] = [ | |
'Joe Bloggs', | |
123456,/* id out of rand range */ | |
'Manager', | |
'Male', | |
12 | |
]; | |
$initialArray['data'] = $data; | |
//array_filter | |
function thatID($element) | |
{ | |
return $element[1] == 123456; | |
} | |
$start_time = microtime(true); | |
print_r(array_filter($initialArray['data'], 'thatID')); | |
$end_time = microtime(true); | |
$execution_time = ($end_time - $start_time); | |
echo " Execution time of array_filter script = " . $execution_time . " sec"; | |
//foreach | |
$start_time = microtime(true); | |
foreach ($initialArray['data'] as $element) { | |
if ($element[1] == 123456) { | |
print_r($element); | |
} | |
} | |
$end_time = microtime(true); | |
$execution_time = ($end_time - $start_time); | |
echo " Execution time of foreach script = " . $execution_time . " sec"; | |
$start_time = microtime(true); | |
$key = array_search(123456, array_column($initialArray['data'], 1)); | |
print_r($initialArray['data'][$key]); | |
$end_time = microtime(true); | |
$execution_time = ($end_time - $start_time); | |
echo " Execution time of array_search script = " . $execution_time . " sec"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment