2

If I have an array:

$nav = array($nav_1, $nav_2, $nav_3);

and want to check if they are empty with a loop (the real array is much bigger), so that it checks each variable separately, how do I do it?

I want something like this;

$count = 0;

while(count < 3){
     if(empty($nav[$count])) //the loops should go through each value (nav[0], nav[1] etc.)
          //do something
          $count = $count+1;
     }else{
          //do something
          $count = $count+1;
     }
}
1
  • You can use in_array() ? Commented Jan 18, 2014 at 10:59

3 Answers 3

4

Pretty straight-forward with a foreach loop:

$count = 0;
foreach ($nav as $value) {
    if (empty($value)) {
        // empty
        $count++;
    } else {
        // not empty
    }
}

echo 'There were total ', $count, ' empty elements';

If you're trying to check if all the values are empty, then use array_filter():

if (!array_filter($nav)) {
    // all values are empty
}
Sign up to request clarification or add additional context in comments.

1 Comment

I would also say to OP that depending on how your array is built you may need to clean and sanitize the string less things like whitespace get written and cause you headaches further down the road.
0

With the following code you can check if all variables are empty in your array. Is this what you are looking for?

$eachVarEmpty = true;

foreach($nav as $item){
    // if not empty set $eachVarEmpty to false and go break of the loop
    if(!empty(trim($item))){
        $eachVarEmpty = false;
        // go out the loop
        break;
    }
}

Comments

0
$empty = array_reduce($array, function(&$a,$b){return $a &= empty($b);},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.