I’m using this function to search the (highest) array key when a value of userid is found:
function array_search_value($needle,$haystack) {
foreach($haystack as $key => $value) {
if(in_array($needle, $value)) return $key;
}
}
My array looks like this (it’s generated by a simple query):
Array
(
[0] => Array
(
[0] => 1
[userid] => 1
[1] => 2
[score1] => 2
[2] => 0
[score2] => 0
)
[1] => Array
(
[0] => 3
[userid] => 3
[1] => 2
[score1] => 2
[2] => 2
[score2] => 2
)
[2] => Array
(
[0] => 4
[userid] => 4
[1] => 1
[score1] => 1
[2] => 1
[score2] => 1
)
[3] =>
)
This code:
echo array_search_value(4, $r)
Returns 2, which is correct.
Looking for 1 gives 0, which is correct.
However, when I search for 2 (which can’t be found), it returns 0.
This, off course, is not correct… What I want it to do is return nothing at all, not 0.
I’ve tried tweeking the function by adding “== true” but that won’t work either.
Anyone know’s how to fix this?
Thanks a lot!
Looking at your provided array, it is correct. The value
2appears in key0:If you only want to look at the
useridkey, then you can’t just usein_array(), but have to do such: