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?
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.
The includes() method returns true if an array contains a specified value. The includes() method returns false if the value is not found.
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.
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 .
For at least 1 element it would be:
if (!empty($myarray)) {}
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.
I believe if(!empty($myarray))
works too. It will mean you won't run w/e if you get array([0] => '')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With