0

How do I check that a PHP array is not empty?

// If $columns array is not empty...

foreach ($columns as $column) {
  echo $column;
}
4
  • I dont know why the vote to close... So far, three different answers with three different solutions. This is obviously not as simple a question as it first appears. I know there are many ways of checking for an empty array, but there is a lot of debate as to the simplest, most efficient way of doing it. Commented Nov 19, 2013 at 20:53
  • It's actually a very simple question (despite there being several different answers, each of which will work), and well documented in the php docs, which is probably why the vote to close Commented Nov 19, 2013 at 20:55
  • I don't think it gets much simpler than if($array). count would be bad for large arrays, however empty is a good solution as well. Commented Nov 19, 2013 at 20:56
  • Related/Duplicate: stackoverflow.com/questions/15202553/… and stackoverflow.com/questions/4014327/… and stackoverflow.com/questions/2216110/… Commented Nov 19, 2013 at 20:56

3 Answers 3

2

Why bother with functions? Empty arrays will simply return false:

if ($array) {
    // array is not empty
}
Sign up to request clarification or add additional context in comments.

Comments

1

Very simple: using empty() function.

if (!empty($columns)){
   foreach ($columns as $column) {
      echo $column;
   }
}

Also can be used with other types than array.

Comments

1

One way is to use count()

if (count($columns) > 0) {
    foreach ($columns as $column) {
        echo $column;
    }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.