Andy Andy - 1 month ago 4
PHP Question

Is there a way to see if there's data in any array elements with a named key without looping through the whole array?

I'm developing an application in PHP 7 which has a list of users and their dietary requirements.

If any of the users have dietary requirements I need to show a link to a page that can display them; conversley if none of the users have such requirements then this isn't shown.

My

$users
array looks like this:

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


So in the above example, Bob has dietary requirements and the button needs to be shown.

My plan to determine whether or not to show the button involves looping through the whole
$users
array, and if it finds any
'diet'
array elements which aren't empty, it shows the button, e.g.

$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 do any of the array elements with a key 'diet' have data in them?

Answer

You could just use a combination of array_filter and array_column to extract the column you want, then check if it's empty...

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

Alternatively:

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