Checking if all the array items are empty PHP

PhpArraysValidation

Php Problem Overview


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>';

Php Solutions


Solution 1 - Php

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>';
}

Solution 2 - Php

Implode the array with an empty glue and check the size of the resulting string:

<?php if (strlen(implode($array)) == 0) echo 'all values of $array are empty'; ?>

> Please note this is a safe way to consider values like 0 or "0" as not empty. The accepted answer using an empty array_filter callback will consider such values empty, as it uses the empty() function. Many form usages would have to consider 0 as valid answers so be careful when choosing which method works best for you.

Solution 3 - Php

An older question but thought I'd pop in my solution as it hasn't been listed above.

function isArrayEmpty(array $array): bool {
	foreach($array as $key => $val) {
		if ($val !== '' || $val !== null) // remove null check if you only want to check for empty strings
			return false;
	}
	return true;
}

Solution 4 - Php

you don't really need it.
You're going to validate these fields separately and by finishing this process you can tell if array was empty (or contains invalid values, which is the same)

Solution 5 - Php

simplify use this way:

$array = []; //target array
$is_empty = true; //flag

foreach ($array as $key => $value) {
    if ($value != '')
        $is_empty = false;
}
if ($is_empty)
    echo 'array is empty!';
else
    echo 'array is not empty!';

Solution 6 - Php

I had the same question but wanted to check each element in the array separately to see which one was empty. This was harder than expected as you need to create the key values and the actual values in separate arrays to check and respond to the empty array element.

print_r($requestDecoded);
$arrayValues = array_values($requestDecoded);  //Create array of values
$arrayKeys = array_keys($requestDecoded);      //Create array of keys to count
$count = count($arrayKeys);
for($i = 0; $i < $count; $i++){  
    if ( empty ($arrayValues[$i] ) ) {         //Check which value is empty
        echo $arrayKeys[$i]. " can't be empty.\r\n";
    } 
}

Result:

Array
(
    [PONumber] => F12345
    [CompanyName] => Test
    [CompanyNum] => 222222
    [ProductName] => Test
    [Quantity] =>
    [Manufacturer] => Test
)

Quantity can't be empty.

Solution 7 - Php

this is pretty simple:

foreach($array as $k => $v)
{
    if(empty($v))
    {
        unset($array[$k]);
    }
}
$show_error = count($array) == 0;

you would also have to change your encapsulation for your array values to double quotes.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMattView Question on Stackoverflow
Solution 1 - PhpxzyferView Answer on Stackoverflow
Solution 2 - PhpCapsuleView Answer on Stackoverflow
Solution 3 - PhpJacob MulquinView Answer on Stackoverflow
Solution 4 - PhpYour Common SenseView Answer on Stackoverflow
Solution 5 - PhpMehran NasrView Answer on Stackoverflow
Solution 6 - PhpCosworth66View Answer on Stackoverflow
Solution 7 - PhpRobertPittView Answer on Stackoverflow