I need to check if a value exists in a multidimensional array. I found this example on Stackoverflow and on PHP.NET which I like because its an elegant and compact solution, but I noticed a weird behavior:
$userdb=Array
(
(0) => Array
(
(uid) => '100',
(name) => 'Sandra Shush',
(pic_square) => 'urlof100'
),
(1) => Array
(
(uid) => '5465',
(name) => 'Stefanie Mcmohn',
(pic_square) => 'urlof100'
),
(2) => Array
(
(uid) => '40489',
(name) => 'Michael',
(pic_square) => 'urlof40489'
)
);
if(array_search(100, array_column($userdb, 'uid'))) {
echo "FOUND";
}
The IF statement does not return any value if you check the existence of any value of the FIRST array (Array [0]
). It does work with the values of the other arrays. Try with 100
first, then try with 40489
(or try with a "name" or "pic_square").
That's because
array_search
returns the key, which in this case is0
, which will equate to false. You need to do a strict comparison, ie:See here
It is because, your value
100
is in first index0
, so if condition fails. Instead compare withfalse
strictly:DEMO
For this instance, it is better to use
in_array
, since you are just checking like if the element is in array or not. Use,array_search
if you want to retrieve the index of the element.You can use
in_array()
like below:-Output:- https://eval.in/1058147
Note:- you code will work also if you modify your comparison like below:-
through the manual:- http://php.net/manual/en/function.array-search.php
It sates:-
php
treated0
asfalse
and1
astrue
. That's why your code fails, because your code returns0
(as match found on the very first index of array).You May Try This: