0

I have the following array which I obtain using sql from cake..

array (size=2)
  0 => 
    array (size=2)
      'users' => 
        array (size=1)
          'user_status' => boolean false
      0 => 
        array (size=1)
          'user_count' => string '17' (length=2)
  1 => 
    array (size=2)
      'users' => 
        array (size=1)
          'user_status' => boolean true
      0 => 
        array (size=1)
          'user_count' => string '4' (length=1)

I have a flag field for active/not active users, which holds boolean value either, true or false. I woul like to iterate over that array and change the value of false to not active, and true to active.

I tried this but it doesn't work

foreach($results as $result){
        if($result['users']['user_status'] == false){
            $result['users']['user_status'] = 'not active';
        }else{
            $result['users']['user_status'] = 'active';
        }
    }

Any other way could do this?

1 Answer 1

2
foreach($results as &$result) {
    if($result['users']['user_status'] === false){
        $result['users']['user_status'] = 'not active';
    } else {
        $result['users']['user_status'] = 'active';
    }
}

This way you are saving the values in the $results array

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks cornelb! How does this work exactly? I have been using php for about 10 months know but never came across this.
You can read more about references here php.net/manual/en/language.references.php
Long story short, without reference (the &) you're copying each iteration into $result, so any modification to this variable won't affect $results. But by reference, you're able to modify the original array by modifying $result

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.