Check if value is set into PHP array's elements

Viewed 169

I have the following array called $users:

$users [2 elements]
0: 
(array) [4 elements]
id: (string) "5"
user_id: (null) 5
email: (string) "test@test.com"
activated: (integer) 0 

1: 
(array) [4 elements]
id: (string) "6"
user_id: (null) 6
email: (string) "test1@test.com"
activated: (integer) 1 

I want to display something in HTML only if any of array's elements have activated set to 1. Can be all, can be only one.

I tried with if( in_array(['actived'] == 1, $users)) with no success.

How do I achieve this?

3 Answers

Use array_column() to get all activated values and search in them:

if (in_array(1, array_column($users, 'activated'), true))

try this if($users->activated == 1)

You could do it while you're iterating the array in the loop

foreach ($users as $user) {
    if ($user['activated'] === 1) {
        // echo html here
    }
}

Or squeezed inside an html markup:

<?php foreach ($users as $user): ?>
    <?php if ($user['activated'] === 1): ?>
    <tr>
        <td><?php echo $user['email']; ?></td> // and others
    </tr>
    <?php endif; ?>
<?php endforeach; ?>

Or you could filter out all items inside using array_filter:

$filtered_users = array_filter($users, function($user) {
    return $user['activated'] === 1; // get all user with activated key with value 1
});

Of course, if it came from mysql db, it would be better just to use a WHERE clause:

SELECT id, user_id, email, activated FROM users WHERE activated = 1
Related