Is there a way to see if there is data in any elements of an array with a named key without a loop through the entire array?

I am developing a PHP 7 application that has a list of users and their dietary requirements.

If any users have dietary requirements, I need to show a link to a page that can display them; if none users have such requirements, then this is not displayed.

My array $userslooks like this:

[
    [ 'name' => 'Andy', 'diet' => '' ],
    [ 'name' => 'Bob', 'diet' => 'Vegeterian' ],
    [ 'name' => 'John', 'diet' => '' ]
]

So, in the example above, Bob has dietary requirements, and a button should be shown.

My plan to determine whether to show or not the button includes a loop through the entire array $users, and if it finds any elements of the array 'diet'that are not empty, it shows the button, for example.

$show_dietary_button = false;
foreach ($users as $user) {
    if ($user['diet'] !== '') {
       $show_dietary_button = true;
       break;
    }
}

if ($show_dietary_button) {
    echo '<a href="#">Show Dietary Requirements</a>';
}

Is there an easier way to do this, i.e. a way to say that any of the elements of the array with the key "diet" had data in them?

+4
source share
1 answer

You can simply use the combination array_filterand array_columnto retrieve the desired column, and then check to see if it is empty ...

if (!empty(array_filter(array_column($records, 'diet')))) {
    $show_dietary_button = true;
}

As an alternative:

$show_dietary_button = !empty(array_filter(array_column($records, 'diet')));
+2
source

Source: https://habr.com/ru/post/1659529/


All Articles