0

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

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

foreach ($columns as $column) {
  echo $column;
}
MultiDev
  • 9,449
  • 22
  • 69
  • 132
  • 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. – MultiDev Nov 19 '13 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 – Mark Baker Nov 19 '13 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. – Rogue Nov 19 '13 at 20:56
  • Related/Duplicate: http://stackoverflow.com/questions/15202553/best-way-to-check-if-php-array-is-empty?lq=1 and http://stackoverflow.com/questions/4014327/best-way-to-check-a-empty-array?lq=1 and http://stackoverflow.com/questions/2216110/checking-for-empty-arrays-count-vs-empty?lq=1 – Justin Nov 19 '13 at 20:56

3 Answers3

2

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

if ($array) {
    // array is not empty
}
Rogue
  • 9,871
  • 4
  • 37
  • 66
1

One way is to use count()

if (count($columns) > 0) {
    foreach ($columns as $column) {
        echo $column;
    }
}
John Conde
  • 207,509
  • 96
  • 428
  • 469
1

Very simple: using empty() function.

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

Also can be used with other types than array.

vikingmaster
  • 7,637
  • 1
  • 20
  • 38