php – What is the best way to check if there are no elements in an array?

Question:

Which of the options is the most correct for checking the php array for the absence of elements in it?

  1. if ($arr) {...}
  2. if (empty($arr)) {...}
  3. if (isset($arr[0])) {...}
  4. if (count($arr)) {...}

Answer:

Yes, everything is generally correct. Only in the first and fourth cases there will be a type conversion to bool, and the third is suitable only for index arrays. There is another option sizeof($arr) .

Scroll to Top