Skip to content
Advertisement

PHP in_array function doesn’t find value

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.

Advertisement

Answer

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";
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement