-2

I've this array :

Array ( [0] => test1 [1] => test2 [2] => test3 [3] => [4] => test4 )

I want to check if any array item is empty or not, as you can see, there's en empty item into my array : [3] => [4] => test4

So I wrote this condition :

           foreach ($array1 as $value) {

              if(!isset($value)) {
                echo "EMPTY";
              } else {
                echo "Not empty";
             }
          }

But it echo Not empty every time, there must have empty for one item

Thanks for your help !

1

5 Answers 5

2

You have to check like this:

foreach ($array1 as $value) {
    if ($value) {
        echo "Not empty";
    } else {
        echo "empty";
    }
}

It will display "empty" when there is an empty array or '' or zero value or null. Hope this helps.

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

Comments

0

Php give you empty() function for the task. empty() will determine whether a variable is empty.

 if(empty($value)) {
        echo "EMPTY";
    } else {
        echo "Not empty";
    }

Comments

0

A good comparative study here

In place of isset you may have to use is_null.

Comments

0

For your query I can suggest following will be solution if values are string

$array1 = array(0 => 'test1', 1 => 'test2', 2 => 'test3', 3 => '',4 => 'test4');
foreach ($array1 as $value) {
              if($value =="") {
                echo "EMPTY";
              } else {
                echo "Not empty";
             }
          }

There is good link that will help you to understand the difference

Comments

-1

Please change your code with below code.

 foreach ($array1 as $value) {    
      if(!empty($value)) {
            echo "Not empty";
      } else {
            echo "EMPTY";
      }
 }

Note : isset() function not check the empty value. It's only check variable is set or not.

2 Comments

isset && !empty is superfluous. Just use !empty. In fact, just use !$value, which will do just fine.
@deceze, Yes it's good but isset() not affected.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.