I have this PHP variable:
$values = $response->getValues();
That print this array:
Array ( [0] => Array ( [0] => 16777439-3 ) [1] => Array ( [0] => 17425847-3 ) )
Then I have this code to find a value inside of that array:
if (in_array("16777439-3", $values)) {
echo "Is in array";
}else{
echo "Isn't in array";
}
But all the time it returns " Isn't in array "
Also I've tried to convert my original variable with:
$array2 = json_decode(json_encode($values), true);
But also I'm getting the same return.
Your values array looks like this:
[
0 => [
0 => "16777439-3"
],
1 => [
0 => "17425847-3"
]
]
Your top level elements are arrays themselves. in_array
can't do a nested search like this. It would only work if your array was just
[
0 => "16777439-3"
1 => "17425847-3"
]
Either change your structure to not use a nested array, or implement a custom search function:
function custom_in_array($search, $haystack){
foreach($haystack as $key => $value)
{
if(in_array($search, $value))
return true;
}
return false;
}
$values is an array of arrays, not an array of strings.
To illustrate, try:
if (in_array("16777439-3", $values[0] )) {
echo "Is in array";
}else{
echo "Isn't in array";
}
You'll have to to some processing to convert $response->getValues() into an array of strings
You have a multi-dimensional array, so just extract the 0
columns with array_column
:
if (in_array("16777439-3", array_column($values, 0))) {
echo "Is in array";
} else {
echo "Isn't in array";
}
Or flatten the array with array_merge
:
if (in_array("16777439-3", array_merge(...$array))) {
echo "Is in array";
} else {
echo "Isn't in array";
}
Also, checking if an index isset
is faster, so you can just re-index on the 0
value and check if that index is set:
if (isset(array_column($values, null, 0)["16777439-3"])) {
echo "Is in array";
} else {
echo "Isn't in array";
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.