TMTOWTDI. Here are several solutions in order of complexity.
(Short primer on complexity follows):O(n)
or "big o" means worst case scenario where n
means the number of elements in the array, and o(n)
or "little o" means best case scenario. Long discrete math story short, you only really have to worry about the worst case scenario, and make sure it's not n ^ 2
or n!
. It's more a measure of change in computing time as n
increases than it is overall computing time. Wikipedia has a good article about computational aka time complexity.
If experience has taught me anything, it's that spending too much time optimizing your programs' little-o is a distinct waste of time better spent doing something - anything - better.
Solution 0: O(n) / o(1)
complexity:
This solution has a best case scenario of 1 comparison - 1 iteration thru the loop, but only provided the matching value is in position 0 of the array. The worst case scenario is it's not in the array, and thus has to iterate over every element of the array.
foreach ($my_array as $sub_array) {
if (@$sub_array['id'] === 152) {
return true;
}
}
return false;
Solution 1: O(n) / o(n)
complexity:
This solution must loop thru the entire array no matter where the matching value is, so it's always going to be n
iterations thru the array.
return 0 < count(
array_filter(
$my_array,
function ($a) {
return array_key_exists('id', $a) && $a['id'] == 152;
}
)
);
Solution 2: O(n log n) / o(n log n)
complexity:
A hash insertion is where the log n
comes from; n
hash insertions = n * log n
. There's a hash lookup at the end which is another log n
but it's not included because that's just how discrete math works.
$existence_hash = [];
foreach ($my_array as $sub_array) {
$existence_hash[$sub_array['id']] = true;
}
return @$existence_hash['152'];