简体   繁体   中英

How to check whether a value exists in an associative array

I have an array that is the result of a SELECT query and would like to check whether a certain value exists in that array.
I tried the following but this does not find the value and always returns that the value does not exist in the array.

I am assuming I am referring wrongly to the array. Can someone show me how to do this right?

My array:

array ( 0 => array ( 'itemName' => 'bandwidth', 'itemType' => 'number', 'itemUnit' => 'mbit', ), 1 => array ( 'itemName' => 'bSize', 'itemType' => 'number', 'itemUnit' => 'sqm', ), 2 => array ( 'itemName' => 'bArea', 'itemType' => 'number', 'itemUnit' => 'sqm', ), )

My PHP:

// ...
$resultC = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
var_export($resultC);
if(in_array('bandwidth', $resultC)) {
    echo 'exists in array';
} else {
    echo 'does not exist in array';
}

You may use the combination of array_column with in_array for your case.

$resultC = [
    0 => ['itemName' => 'bandwidth', 'itemType' => 'number', 'itemUnit' => 'mbit'],
    1 => ['itemName' => 'bSize', 'itemType' => 'number', 'itemUnit' => 'sqm'],
    2 => ['itemName' => 'bArea', 'itemType' => 'number', 'itemUnit' => 'sqm'],
];

return in_array('bandwidth', array_column($resultC, 'itemName'));

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM