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:
<code class="php">$array = array( 'RequestID' => $_POST["RequestID"], 'ClientName' => $_POST["ClientName"], 'Username' => $_POST["Username"], 'RequestAssignee' => $_POST["RequestAssignee"], 'Status' => $_POST["Status"], 'Priority' => $_POST["Priority"] );</code>
To check if all the array elements are empty, you can use the built-in array_filter function as follows:
<code class="php">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>'; }</code>
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.
The above is the detailed content of How to Validate if All Entries in an Array are Empty in PHP?. For more information, please follow other related articles on the PHP Chinese website!