0

I have the following array structure:

  0 => 
    array
      'all_sessions_available' => boolean true
      'all_sessions_unavailable' => boolean false
  ....
  22 => 
    array
      'all_sessions_available' => boolean false
      'all_sessions_unavailable' => boolean true

I am trying to remove the full array element if all_sessions_unavailable = true

I have the following code:

for ($i = 0; $i <= count($processData); $i++) {
    if ($processData[$i]['all_sessions_unavailable'] === true) {
        unset($processData[$i]);
    }
}

However it removes all but the last array (22 in this case which happens to be the last array in the overall array if that makes any difference)

Is there something I'm doing wrong?

2
  • not 100% sure on this but try iterating from the other side... I think it is changing the indexes as it unsets so instead do "for($i=count($processData);$i>=0;$i--)" Commented May 13, 2012 at 23:13
  • That worked a treat, make it an answer :) Commented May 13, 2012 at 23:19

3 Answers 3

1

I think it is changing the indexes as it unsets so instead do

 for($i=count($processData);$i>=0;$i--)
Sign up to request clarification or add additional context in comments.

Comments

1

An alternative approach for PHP 5.3+:

$processData = array_filter($processData,
                            function ($i) { return !$i['all_sessions_unavailable']; });

Comments

1
foreach($processData as $index=>$session){
    if($session['all_sessions_unavailable']){
        unset($processData[$index]);
    }
}

Why don't you just use foreach(), it's probably one of the best features in PHP...

Also, unless all_sessions_unavailable could contain values other than boolean, you don't have to match it against an exact true.

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.