I'm adding an array of items from a form and if all of them are empty, I want to perform some validation and add to an error string. So I have:
$array = array( 'RequestID' => $_POST["RequestID"], 'ClientName' => $_POST["ClientName"], 'Username' => $_POST["Username"], 'RequestAssignee' => $_POST["RequestAssignee"], 'Status' => $_POST["Status"], 'Priority' => $_POST["Priority"] );
And then if all of the array elements are empty perform:
$error_str .= '<li>Please enter a value into at least one of the fields regarding the request you are searching for.</li>';
To check if all of the values in an array are equal to null , use the every() method to iterate over the array and compare each value to null , e.g. arr. every(value => value === null) . The every method will return true if all values in the array are equal to null .
Use NOT Operator to Check Whether an Array Is Empty in PHP php $emptyArray = array(); if(! $emptyArray) echo("The array is empty."); ?> Output: The array is empty.
PHP empty() Function The empty() function checks whether a variable is empty or not. This function returns false if the variable exists and is not empty, otherwise it returns true.
For example, in PHP, empty arrays are falsy, but in JavaScript arrays are always truthy.
You can just use the built in array_filter
If no callback is supplied, all entries of input equal to FALSE (see converting to boolean) will be removed.
So can do this in one simple line.
if(!array_filter($array)) { echo '<li>Please enter a value into at least one of the fields regarding the request you are searching for.</li>'; }
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