Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if all the array items are empty PHP

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>'; 
like image 459
Matt Avatar asked Feb 18 '11 11:02

Matt


People also ask

How do you check if all elements in an array are empty?

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 .

How can check array value is not empty in PHP?

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.

How check data is empty or not in PHP?

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.

Is empty array falsey PHP?

For example, in PHP, empty arrays are falsy, but in JavaScript arrays are always truthy.


1 Answers

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>'; } 
like image 62
xzyfer Avatar answered Oct 17 '22 06:10

xzyfer