简体   繁体   中英

How to check if array contains certain value for specific key when the parent array is not associative?

I have the following array that contains associative arrays:

array(
    [0] => array ("name" => "foo", //more key-value pairs)
    [1] => array ("name" => "bar", //more key-value pairs)
    [2] => array ("name" => "baz", //more key-value pairs)
)

How can I check if a name exists while iterating over another array of names:

foreach ($list_of_names as $name) {
    // does the current name exist in the other array?
}

Is there a way to do it without nesting foreach loop inside the foreach loop?

Your question is a bit vague. I understand that you ask whether it is possible to check if any of the inner arrays contains a given key without using two nested foreach loops.

If so then take a look at this example:

<?php
$data = [
    ["name-foo" => "foo"],
    ["name-bar" => "bar"],
    ["name-baz" => "baz"],
];
$needle = "name-bar";
array_walk($data, function($entry) use ($needle) {
    var_dump(
        array_key_exists($needle, $entry) 
        ? "$needle exists" 
        : "$needle does NOT exist"
    );
});

The output obviously is:

string(23) "name-bar does NOT exist"
string(15) "name-bar exists"
string(23) "name-bar does NOT exist"

In the end there is no way around having to iterate over all entries in the nested arrays. But you don't have to do that explicitly in the calling scope, you can use the many convenience functions php offers, here array_key_exists(...) for example.

If you just need to know if the name exists, you could extract the name values (using array_column() ) and (in this case) using aray_flip() to make it an associative array. This allows you to use isset() inside the loop and not have to do any nested loops.

$data = [
    ['name' => 'foo'], //more key-value pairs)
    ['name' => 'bar'], //more key-value pairs)
    ['name' => 'baz'], //more key-value pairs)
];

$list_of_names = [
    'foo',
    'bart'
];
$dataNames = array_flip(array_column($data, 'name'));
foreach ($list_of_names as $name) {
    if (isset($dataNames[$name])) {
        echo "$name exists" . PHP_EOL;
    } else {
        echo "$name does not exist" . PHP_EOL;
    }
}

will show

foo exists
bart does not exist

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