Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test if array contains at least one element

Tags:

php

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?

like image 832
PeeHaa Avatar asked Jan 13 '12 23:01

PeeHaa


People also ask

How do you check if an array has at least one element?

some() The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise it returns false.

How do you check if an array has a certain element?

The includes() method returns true if an array contains a specified value. The includes() method returns false if the value is not found.

What array method can be used to check if at least one array element satisfies some condition?

The Array type provides you with an instance method called some() that allows you to test if an array has at least one element that meets a condition. The condition is implemented via a callback function passed into the some() method.

How do you check if an array contains multiple values?

To check if multiple values exist in an array: Use the every() method to iterate over the array of values. On each iteration, use the indexOf method to check if the value is contained in the other array. If all values exist in the array, the every method will return true .


3 Answers

For at least 1 element it would be:

if (!empty($myarray)) {}
like image 107
Liam Bailey Avatar answered Oct 26 '22 22:10

Liam Bailey


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.

like image 45
miku Avatar answered Oct 26 '22 23:10

miku


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

like image 35
Biotox Avatar answered Oct 27 '22 00:10

Biotox