Validating Empty Array Items in PHP
When receiving an array of items from a form, you may need to validate whether all of them are empty. If they are, you can trigger specific validation and add error messages.
Consider the following array of items:
$array = array(
'RequestID' => $_POST["RequestID"],
'ClientName' => $_POST["ClientName"],
'Username' => $_POST["Username"],
'RequestAssignee' => $_POST["RequestAssignee"],
'Status' => $_POST["Status"],
'Priority' => $_POST["Priority"]
);
To check if all the array elements are empty, you can use the built-in array_filter function as follows:
if(!array_filter($array)) {
echo 'Please enter a value into at least one of the fields regarding the request you are searching for. ';
}
This approach uses the array_filter function without providing a callback. As a result, it will remove all entries that evaluate to FALSE (equivalent to an empty value) from the array. If the resulting array is empty, it means all elements were empty, and the error message will be displayed.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3