-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,372
  • 15
  • 66
  • 132
max
  • 313
  • 3
  • 4
  • 10

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
  • 39,820
  • 10
  • 58
  • 75
1

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

empty — Determine whether a variable is empty

if (empty($myarray)) {}
Jordi Nebot
  • 3,228
  • 3
  • 28
  • 50