Checking If All the Array Items Are Empty PHP

Checking if all the array items are empty 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>';
}

Determine if all the values in a PHP array are null

function containsOnlyNull($input)
{
return empty(array_filter($input, function ($a) { return $a !== null;}));
}

How to check whether an array is empty using PHP?

If you just need to check if there are ANY elements in the array, you can use either the array itself, due to PHP's loose typing, or - if you prefer a stricter approach - use count():

if (!$playerlist) {
// list is empty.
}
if (count($playerlist) === 0) {
// list is empty.
}

If you need to clean out empty values before checking (generally done to prevent explodeing weird strings):

foreach ($playerlist as $key => $value) {
if (!strlen($value)) {
unset($playerlist[$key]);
}
}
if (!$playerlist) {
//empty array
}

How do I check if array value is empty?

It works as expected, third one is empty

http://codepad.org/yBIVBHj0

Maybe try to trim its value, just in case that third value would be just a space.

foreach ($array as $key => $value) {
$value = trim($value);
if (empty($value))
echo "$key empty <br/>";
else
echo "$key not empty <br/>";
}

How to see if an array of associative arrays is empty in php

If you're looking for a one-liner then you could do something like:

$form_values = array (
'person1' =>
array (
),
'person2' =>
array (
),
'person3' =>
array (
),
);

if(array_sum(array_map(function($v){return !empty($v);}, $form_values)) === 0)
{
// empty
}
else
{
// not empty
}

PHP Checking if Array is empty logic not working

Use empty() function.

empty() - it will return true if the variable is an empty string, false, array(), NULL, “0?, 0, and an unset variable.

Syntax

empty(var_name)

Return value

FALSE if var_name has a non-empty and non-zero value.

Value Type :

Boolean

List of empty things :

  • "0" (0 as a string)
  • 0 (0 as an integer)
  • "" (an empty string)
  • NULL
  • FALSE
  • "" (an empty string)
  • array() (an empty array)
  • $var_name; (a variable declared but without a value in a class)

Code

if (!empty($_SESSION['selectedItemIDs']) ) {
// update the selections in a database
} else {
// nothing selection so just record this in a variable
$selectedItems = 'no selected items were made';
}

Find if an array is empty in PHP

Your array is not empty, you have assigned 4 keys without value.

empty($array_new)    // false
empty($array_new[0]) // true

To remove empty values from array use:

$filtered = array_filter($array_new, function ($var) {
return !is_null($var);
});

Documentation:

  • empty()
  • array_filter()


Related Topics



Leave a reply



Submit