0

I am having difficulties in changing the values of a nested array. I am trying to change the 'admin' => '1'value to 'admin' => '0' of each nested array. I tried a foreach loop but the logic is not correct. How can I correct this? or is there a better way?

Array

'user' => array(
        // Regular user, admin
    array(
       'id' = '1'
       'admin' => '1',
       ),
    array(
        'id' = '2'
        'admin' => '1',
        ),
    array(
       'id' = '3'
       'admin' => '1',
       ),
    )

Loop:

foreach ($users as $admin => $value) {
        if ($value == 1) {
            $value == 0;
        }
    }

3 Answers 3

1

You need to pass the value by reference if you want to edit it in the source array.

foreach ($users as $admin => &$value) {
    if ($value['admin'] == 1) {
        $value['admin'] = 0;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

you forgot to pass 'admin' key for $value in foreach statement

use

      $value['admin']

Comments

0

You are checking the type of admin twice (==). You need the assignment statement of =. You also need to access the admin key of the array you are looping on.

This should be more like it:

foreach ($users as $admin => $value) {
        if ($value['admin'] == 1) {
//                ^ Use ['key'] to access the value of that key 
            $value['admin'] = '0';
//                          ^ This assigns 0 to the value.
        }
    }

Comments

Your Answer

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