How to check if a PHP array has any value set?
Perhaps empty()?
From Docs:
Return Values
Returns FALSE if var has a non-empty and non-zero value.
The following things are considered to be empty:
"" (an empty string) 0 (0 as an integer) "0" (0 as a string) NULL FALSE array() (an empty array) var $var; (a variable declared, but without a value in a class)
if ($signup_errors) {
// there was an error
} else {
// there wasn't
}
How does it work? When converting to boolean, an empty array converts to false. Every other array converts to true. From the PHP manual:
Converting to boolean
To explicitly convert a value to boolean, use the (bool) or (boolean) casts. However, in most cases the cast is unncecessary, since a value will be automatically converted if an operator, function or control structure requires a boolean argument.
See also Type Juggling.
When converting to boolean, the following values are considered FALSE:
- the boolean FALSE itself
- the integer 0 (zero)
- the float 0.0 (zero)
- the empty string, and the string "0"
- an array with zero elements
- an object with zero member variables (PHP 4 only)
- the special type NULL (including unset variables)
- SimpleXML objects created from empty tags
- Every other value is considered TRUE (including any resource).
You could also use empty()
as it has similar semantics.