-2

I am trying to know if an array is empty, as I am still learning to use php I would like to know which is the best way .. now I am doing it this way:

if (sizeof($myarray) == 0) { }
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
max
  • 353
  • 3
  • 4
  • 12

2 Answers2

2

If you know that the variable exists, then

if (!$myarray) { }

is probably the simplest, amount-of-code-wise. (Empty arrays evaluate as false.) If you're not sure whether or not it exists, then

if (empty($myarray)) { }

will avoid undefined variable notices as well.

Counting it is unnecessary work if all you need is to see whether or not it's empty.

Don't Panic
  • 41,125
  • 10
  • 61
  • 80
1

I'd say empty() is the best way:

empty — Determine whether a variable is empty

if (empty($myarray)) {}
Jordi Nebot
  • 3,355
  • 3
  • 27
  • 56