Have some problems with checking if a value exists in a 2d array. I have a field in my database table where I save my data in JSON
. I parse it this way:
$this_will_be_saved = json_encode($array);
Now I need to add some data to the array, but I need to check if the array already has that item:
$this_will_be_saved = json_decode($this_will_be_saved, true);
Decoded array structure:
array(5) {
[0]=>
array(2) {
["rating"]=>
int(9)
["userid"]=>
int(1)
}
[1]=>
array(2) {
["rating"]=>
int(9)
["userid"]=>
int(1)
}
[2]=>
array(2) {
["rating"]=>
int(9)
["userid"]=>
int(1)
}
[3]=>
array(2) {
["rating"]=>
int(1)
["userid"]=>
int(1)
}
[4]=>
array(2) {
["rating"]=>
int(7)
["userid"]=>
int(1)
}
}
I try check if new added value exist in array but array_search not working :/
$key = array_search($userid, array_column($this_will_be_saved, 'userid'));
if ( $key ) {
// found
} else {
// not found
}
It's never finding anything, even if the user id is already in a row.
array_search()
returns the first corresponding key, if it finds the value in the array.
The first key of your array is 0
that is the same as false
(returned by array_search()
when it cannot find the value in the array) when evaluated in boolean context.
An if
expression is such a context (if ($key)
in your code).
Accordingly, if $userid
is 1
, array_search()
returns 0
and the if
statement correctly takes the else
branch.
Use in_array()
to check if a value exists in an array:
$found = in_array($userid, array_column($this_will_be_saved, 'userid'));
if ($found) {
// found
} else {
// not found
}