Php check that array is empty

Check PHP array is empty or not?

Now I need to check, this bank array is empty or not. That mean all index should have a value. This is how I tried it:

$proceed = false; foreach ($empData[$employee]['banks'] as $key) < echo '
', print_r($key).'

‘; foreach ($key as $k => $v) < if (empty($empData[$employee]['banks'][$k]))< $proceed = true; break; >> > if(!$proceed) < echo 'This array is empty'; >else
But, Its not working for me. Its always going to else part, even if the array is not empty. UPDATE:

$proceed = false; foreach ($empData[$employee]['banks'] as $bank) < if (!array_filter($bank)) < $proceed = true; break; >> if($proceed) < echo 'This array is empty'; >else
This array is not empty Array ( [0] => Array ( [bank_name] => Bank Name [bank_code] => 7083 [branch] => Branch Name [account_number] => 234234324242 [account_type] => NRFC ) ) 
This array is not empty Array ( [0] => Array ( [bank_name] => [] [bank_code] => [branch] => [account_number] => [account_type] => ) ) 

Why do you fully qualify the path inside the array, rather than simply using empty($v) or empty($key[$k]) ?

If I am reading it right — you are setting $proceed to true if the array is empty but then are in your if statement — it is expecting $proceed to be false in order to echo that its empty. But I coud be wrong

set $proceed to false if the array is empty — «. if (empty($empData[$employee][‘banks’][$k]))< $proceed = false;.

6 Answers 6

Your question has been updated a couple times. It looks like you might want to consider a $bank as «empty» if one of the values are unpopulated – my original answer (below) will only return true if all values match the function. What we’d need to accommodate this is a slightly different function, array_some .

function array_some(callable $f, array $xs) < foreach (array_values($xs) as $x) if (call_user_func($f, $x)) return true; return false; >$input = [ [ 'bank_name' => [], 'bank_code' => null, 'branch' => null, 'account_number' => null, 'accout_type' => null ], [ 'bank_name' => ['foobar'], 'bank_code' => 123, 'branch' => null, 'account_number' => null, 'accout_type' => null ], [ 'bank_name' => 'Bank Name', 'bank_code' => 7083, 'branch' => 'Branch Name', 'account_number' => '234234324242', 'accout_type' => 'NRFC' ] ]; function is_empty($x) < return empty($x); >foreach ($input as $bank) < $proceed = array_some('is_empty', $bank); echo 'proceed:', json_encode($proceed), PHP_EOL; >// proceed:true // proceed:true // proceed:false 
  • In the first example, some fields are empty, so $proceed will be true
  • In the second example, some fields are empty, so $proceed will be true
  • In the third example, all fields are non-empty, so $proceed will be false

ORIGINAL ANSWER:

What you’re looking for is an array_every function. Let’s start with a simple example:

function array_every(callable $f, array $xs) < foreach (array_values($xs) as $x) if (!call_user_func($f, $x)) return false; return true; >function even($x) < return $x % 2 === 0; >echo "even:", json_encode(array_every('even', [1,2,3])), PHP_EOL; // false echo "even:", json_encode(array_every('even', [2,4,6])), PHP_EOL; // true 
  • In the first example, 1 , 2 , and 3 are not all even , so the output is false.
  • In the second example, 2 , 4 , and 6 are all even , so the output is true.

Let’s see it with your data now

function array_every(callable $f, array $xs) < foreach (array_values($xs) as $x) if (!call_user_func($f, $x)) return false; return true; >$input = [ [ 'bank_name' => [], 'bank_code' => null, 'branch' => null, 'account_number' => null, 'accout_type' => null ], [ 'bank_name' => ['foobar'], 'bank_code' => 123, 'branch' => null, 'account_number' => null, 'accout_type' => null ] ]; function is_empty($x) < return empty($x); >foreach ($input as $bank) < $proceed = array_every('is_empty', $bank); echo 'proceed:', json_encode($proceed), PHP_EOL; >// proceed:true // proceed:false 
  • In the first example data, all of the array values are empty , therefore $proceed will be true .
  • In the second example, some of the values are (non- empty ), therefore $proceed will be false .

Note: Because empty is a language construct and not a function, it cannot be called using variable functions. – This is why I defined a reusable is_empty function instead of using array_every(’empty’, . ) – which would not work.

Источник

best way to check a empty array?

A more general and fault tolerant solution than mine :), but could you not short circuit it and return immediately on a non empty answer instead of continuing to test the rest of the array?

@David Martensson: The execution will only be routed to that else statement if the variable given to the function is not an array. Think of the array given in the question as a tree and the else block as the base case that all leaves will be evaluated by.

Yes, but if it is an array it will complete the array and every array higher in the hierarchy even though it might already have found that its not empty. His example clearly specified that you could have empty rows but they should still be considered empty.

Ah I see what you’re saying. Yes, you’re right. Once you find a non-empty element you should stop comparing and return false. My implementation will needlessly continue to check for non-empty elements until it’s traversed the whole structure.

If your array is only one level deep you can also do:

if (strlen(implode('', $array)) == 0) 

Solution with array_walk_recursive:

function empty_recursive($value) < if (is_array($value)) < $empty = TRUE; array_walk_recursive($value, function($item) use (&$empty) < $empty = $empty && empty($item); >); > else < $empty = empty($value); >return $empty; > 

Assuming the array will always contain the same type of data:

function TestNotEmpty($arr) < foreach($arr as $item) if(isset($item->title) || isset($item->descrtiption || isset($item->price)) return true; return false; > 

Short circuiting included.

function hasValues($input, $deepCheck = true) < foreach($input as $value) < if(is_array($value) && $deepCheck) < if($this->hasValues($value, $deepCheck)) return true; > elseif(!empty($value) && !is_array($value)) return true; > return false; > 

Here’s my version. Once it finds a non-empty string in an array, it stops. Plus it properly checks on empty strings, so that a 0 (zero) is not considered an empty string (which would be if you used empty() function). By the way even using this function just for strings has proven invaluable over the years.

function isEmpty($stringOrArray) < if(is_array($stringOrArray)) < foreach($stringOrArray as $value) < if(!isEmpty($value)) < return false; >> return true; > return !strlen($stringOrArray); // this properly checks on empty string ('') > 

If anyone stumbles on this question and needs to check if the entire array is NULL, meaning that each pair in the array is equal to null, this is a handy function. You could very easily modify it to return true if any variable returns NULL as well. I needed this for a certain web form where it updated users data and it was possible for it to come through completely blank, therefor not needing to do any SQL.

$test_ary = array("1"=>NULL, "2"=>NULL, "3"=>NULL); function array_empty($ary, $full_null=false) < $null_count = 0; $ary_count = count($ary); foreach($ary as $value)< if($value == NULL)< $null_count++; >> if($full_null == true)< if($null_count == $ary_count)< return true; >else < return false; >>else < if($null_count >0)< return true; >else < return false; >> > $test = array_empty($test_ary, $full_null=true); echo $test; 
$arr=array_unique(array_values($args)); if(empty($arr[0]) && count($arr)==1)

Returns TRUE if passed a variable other than an array, or if any of the nested arrays contains a value (including falsy values!). Returns FALSE otherwise. Short circuits.

function has_values($var) < if (is_array($var)) < if (empty($var)) return FALSE; foreach ($var as $val) < if(has_values($val)) return TRUE; >return FALSE; > return TRUE; > 

Here’s a good utility function that will return true (1) if the array is empty, or false (0) if not:

function is_array_empty( $mixed ) < if ( is_array($mixed) ) < foreach ($mixed as $value) < if ( ! is_array_empty($value) ) < return false; >> > elseif ( ! empty($mixed) ) < return false; >return true; > 

For example, given a multidimensional array:

$products = array( 'product_data' => array( 0 => array( 'title' => '', 'description' => null, 'price' => '', ), ), ); 

You’ll get a true value returned from is_array_empty() , since there are no values set:

var_dump( is_array_empty($products) ); 

View this code interactively at: http://codepad.org/l2C0Efab

I needed a function to filter an array recursively for non empty values.

Here is my recursive function:

function filterArray(array $array, bool $keepNonArrayValues = false): array < $result = []; foreach ($array as $key =>$value) < if (is_array($value)) < $value = $this->filterArray($value, $keepNonArrayValues); > // keep non empty values anyway // otherwise only if it is not an array and flag $keepNonArrayValues is TRUE if (!empty($value) || (!is_array($value) && $keepNonArrayValues)) < $result[$key] = $value; >> return array_slice($result, 0) > 

With parameter $keepNonArrayValues you can decide if values such 0 (number zero), » (empty string) or false (bool FALSE) shout be kept in the array. In other words: if $keepNonArrayValues = true only empty arrays will be removed from target array.

array_slice($result, 0) has the effect that numeric indices will be rearranged (0..length-1).

Additionally, after filtering the array by this function it can be tested with empty($filterredArray) .

Источник

Check whether an array is empty without using a loop?

Is there any function available in PHP to check whether an array is empty or how can I do this without using loop? For example: $b = array(‘key1’ => », ‘key2’ => », ‘key3’ => », ‘key4’ => »); How can I check array $b contains empty values without using a loop?

Cletus is right when he says that you’ll be looping no matter what, but I am kind of wondering why you want to avoid looping. Is there a reason other than curiosity?

i have large number of values through multi dimensional array. so i thought it would a better if i reject using loops .

Why are you storing empty values? And if you have lots of those in an array with only a couple of non-empty ones, maybe you should think about your data structure. It doesn’t seem optimal.

7 Answers 7

function allEmpty($array) < return empty(array_filter($array)); // (PHP < 5.3) or $array = array_filter($array); return empty($array); // (PHP >= 5.3) or just return array_filter($array) === array(); > function someEmpty($array)

I guess because technically it’s still looping, but it might be arguably better than writing your own loop.

empty() does not use loops, array_filter() does. You can change your definition of «empty» by supplying a custom comparison function to array_filter .

The 1st example does not work. You can’t use a function return value in write context (at least not with PHP 5.3.1).

Whether you use a loop or some array function, you’re still looping through the array so keep it simple and just loop through the array:

function isEmpty($arr) < foreach ($arr as $k =>$v) < if ($v) < return false; >> return true; > 

Depending on what you want to define as empty, you may want to only check for empty strings:

function isEmpty($arr) < foreach ($arr as $k =>$v) < if ($v === '') < return false; >> return true; > 

If you don’t want to do a literal foreach/for/while, you can use array_walk.

If that is the specific array you want to check (ie: it only has key=>values and empty is always key=>») .

$b = array('key1' => '', 'key2' => '', 'key3' => '', 'key4' => ''); $temp = array_flip($b); if(count($temp) === 1 && empty($temp[0]))

Otherwise you are going to have to use a loop. sorry.

if you want to check for empty strings » you can use in_array

if(!in_array('', $array)) echo 'array doesn’t contain empty strings'; if(in_array('', $array)) echo 'array does contain at least one empty string'; 

you might also want to try array_filter with an empty callback method, and compare that to an empty array (or use empty() ):

if(empty(array_filter($array))) echo 'array only contains values evaluating to false'; 

Источник

Читайте также:  Css img filter svg
Оцените статью