Home » Php » php – How to test if array contains at least one element

php – How to test if array contains at least one element

Posted by: admin July 12, 2020 Leave a comment

Questions:

How should I test if an array contains at least 1 element (rather than just being an empty array $myarray = array();)?

Is there a THE way?

E.g.

if ($myarray) { }

if (count($myarray)) { }

if (count($myarray) > 0) { }

Or is there a THE wrong way?

How to&Answers:

For at least 1 element it would be:

if (!empty($myarray)) {}

Answer:

Maybe check for non-emptiness via empty()?

The following things are considered to be empty:

  • “” (an empty string)
  • 0 (0 as an integer)
  • 0.0 (0 as a float)
  • “0” (0 as a string)
  • NULL
  • FALSE
  • array() (an empty array)
  • var $var; (a variable declared, but without a value in a class)
if (!empty($myarray)) { 
    //
}

But I am not sure, if there is one canonical way to do it; php might follow TMTOWTDI.

Answer:

I believe if(!empty($myarray)) works too. It will mean you won’t run w/e if you get array([0] => '')