How to check if an array contains at least one element

How to check if an array contains at least 1 element (and not just an empty array $myarray = array(); )?

Is there any way?

eg.

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

Or is there a wrong way?

+6
source share
3 answers

For at least 1 element, this will be:

 if (!empty($myarray)) {} 
+15
source

Perhaps check for non-emptyness via empty() ?

The following things are considered empty:

  • "(empty line)
  • 0 (0 as an integer)
  • 0.0 (0 as a float)
  • "0" (0 as a string)
  • Null
  • False
  • array () (empty array)
  • var $ var; (declared variable, but no value in the class)
 if (!empty($myarray)) { // } 

But I'm not sure if there is one canonical way to do this; php can follow TMTOWTDI .

+5
source

I believe if(!empty($myarray)) works too. This means that you will not run w / e if you get array([0] => '')

+2
source

Source: https://habr.com/ru/post/905953/


All Articles