2

I have the following array called $users:

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

1: 
(array) [4 elements]
id: (string) "6"
user_id: (null) 6
email: (string) "[email protected]"
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 3

2

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

if (in_array(1, array_column($users, 'activated'), true))
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

Thank you! I managed to fix it before reading it here by doing a loop in my controller and export a variable (pretty much your first solution). Then, in my view, I just check if that var is set and display the content I want.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.