Как проверить пустой ли массив php

от admin

Check Whether an Array Is Empty in PHP

This article will introduce methods to check whether an array is empty in PHP.

  • Using empty() function
  • Using sizeof() function
  • Using count() function
  • Using NOT operator

Use empty() Function to Check Whether an Array Is Empty in PHP

We can use the built-in function empty() to check whether an array is empty. This function checks for all types of variables, including arrays. The correct syntax to use this function is as follows.

The built-in function empty() has only one parameter. The detail of its parameter is as follows

This function returns a Boolean value depending upon the condition of the passed variable. It returns 1 if the variable is empty and returns 0 if the variable is not empty.

The program below shows how we can use this function to check if an array is empty or not.

We have stored the return value of empty() function in $isEmpty variable.

empty

Determine whether a variable is considered to be empty. A variable is considered empty if it does not exist or if its value equals false . empty() does not generate a warning if the variable does not exist.

Parameters

Variable to be checked

No warning is generated if the variable does not exist. That means empty() is essentially the concise equivalent to !isset($var) || $var == false.

Return Values

Returns true if var does not exist or has a value that is empty or equal to zero, aka falsey, see conversion to boolean. Otherwise returns false .

Examples

Example #1 A simple empty() / isset() comparison.

// Evaluates to true because $var is empty
if (empty( $var )) <
echo ‘$var is either 0, empty, or not set at all’ ;
>

// Evaluates as true because $var is set
if (isset( $var )) <
echo ‘$var is set even though it is empty’ ;
>
?>

Example #2 empty() on String Offsets

The above example will output:

Notes

Note: Because this is a language construct and not a function, it cannot be called using variable functions, or named arguments.

Note:

When using empty() on inaccessible object properties, the __isset() overloading method will be called, if declared.

See Also

  • isset() — Determine if a variable is declared and is different than null
  • unset() — Unset a given variable
  • array_key_exists() — Checks if the given key or index exists in the array
  • count() — Counts all elements in an array or in a Countable object
  • strlen() — Get string length

User Contributed Notes 37 notes

<?php
/**
* @author : Nanhe Kumar <nanhe.kumar@gmail.com>
* List of all empty values
**/

foreach ( $testCase as $k => $v ) <
if (empty( $v )) <
echo «<br> $k => $v is empty» ;
>
>
/**
Output
1=> is empty
2=> is empty
3=> is empty
4=>Array is empty
5=> is empty
6=> is empty
7=>0 is empty
8=>0 is empty
**/
?>

Please note that results of empty() when called on non-existing / non-public variables of a class are a bit confusing if using magic method __get (as previously mentioned by nahpeps at gmx dot de). Consider this example:

<?php
class Registry
<
protected $_items = array();
public function __set ( $key , $value )
<
$this -> _items [ $key ] = $value ;
>
public function __get ( $key )
<
if (isset( $this -> _items [ $key ])) <
return $this -> _items [ $key ];
> else <
return null ;
>
>
>

$registry = new Registry ();
$registry -> empty = » ;
$registry -> notEmpty = ‘not empty’ ;

var_dump (empty( $registry -> notExisting )); // true, so far so good
var_dump (empty( $registry -> empty )); // true, so far so good
var_dump (empty( $registry -> notEmpty )); // true, .. say what?
$tmp = $registry -> notEmpty ;
var_dump (empty( $tmp )); // false as expected
?>

The result for empty($registry->notEmpty) is a bit unexpeced as the value is obviously set and non-empty. This is due to the fact that the empty() function uses __isset() magic functin in these cases. Although it’s noted in the documentation above, I think it’s worth mentioning in more detail as the behaviour is not straightforward. In order to achieve desired (expexted?) results, you need to add __isset() magic function to your class:

<?php
class Registry
<
protected $_items = array();
public function __set ( $key , $value )
<
$this -> _items [ $key ] = $value ;
>
public function __get ( $key )
<
if (isset( $this -> _items [ $key ])) <
return $this -> _items [ $key ];
> else <
return null ;
>
>
public function __isset ( $key )
<
if (isset( $this -> _items [ $key ])) <
return ( false === empty( $this -> _items [ $key ]));
> else <
return null ;
>
>
>

$registry = new Registry ();
$registry -> empty = » ;
$registry -> notEmpty = ‘not empty’ ;

var_dump (empty( $registry -> notExisting )); // true, so far so good
var_dump (empty( $registry -> empty )); // true, so far so good
var_dump (empty( $registry -> notEmpty )); // false, finally!
?>

It actually seems that empty() is returning negation of the __isset() magic function result, hence the negation of the empty() result in the __isset() function above.

Multiple empty():
<?php
/**
* Multiple empty().
*
* @param mixed[] $vars Variables to test
* @return bool
*/
function multi_empty (& . $vars )
<
// no callback is supplied, all empty values will be removed
return array_filter ( $vars ) === [];
>
?>
example:
<?php
$notEmptyVar = 1 ;
$emptyVar = null ;
// $undefinedVar — not defined

multi_empty ( $emptyVar ); // true
multi_empty ( $emptyVar , $undefinedVar ); // true
multi_empty ( $notEmptyVar , $emptyVar ); // false
multi_empty ( $notEmptyVar , $emptyVar , $undefinedVar ); // false
?>

When you need to accept these as valid, non-empty values:
— 0 (0 as an integer)
— 0.0 (0 as a float)
— «0» (0 as a string)

<?php
function is_blank ( $value ) <
return empty( $value ) && ! is_numeric ( $value );
>
?>

This is similar to Rails’ blank? method.

I normally count() an array, so I wanted to see how empty() would stack up.

<?php
$test = array();
$test2 = array();
for ( $x = 0 ; $x < 1000 ; $x ++) $test [] = $x ;

$ts = microtime ( true );
for ( $x = 0 ; $x < 100000000 ; $x ++)
<
if ( count ( $test ))
<
>
>

echo «Time taken: » . ( microtime ( true ) — $ts ) . » sec\n» ;
?>

For 100,000,000 comparisons, here are the results against PHP 7.2.16 on my hardware:

count($test): 2.697 sec
count($test2): 2.596 sec
$test === array(): 2.579 sec
$test2 === array(): 2.552 sec
empty($test): 3.085 sec
empty($test2): 3.113 sec

In short, it doesn’t matter what method is used although empty() is actually just ever so slightly slower despite it being a language construct. YMMV.

<?php
$str = ‘ ‘ ;
var_dump (empty( $str )); // boolean false
?>

So remember to trim your strings first!

<?php
$str = ‘ ‘ ;
$str = trim ( $str );
var_dump (empty( $str )); // boolean true
?>

To add on to what anon said, what’s happening in john_jian’s example seems unusual because we don’t see the implicit typecasting going on behind the scenes. What’s really happening is:

(int)$a == $b -> true, because any string that’s not a number gets converted to 0
$b==(int)$c -> true, because the int in the string gets converted
and
$a==$c -> false, because they’re being compared as strings, rather than integers. (int)$a==(int)$c should return true, however.

Note: I don’t remember if PHP even *has* typecasting, much less if this is the correct syntax. I’m just using something for the sake of examples.

(experienced in PHP 5.6.3) The `empty()` can’t evaluate `__get()` results explicitly, so the `empty()` statement bellow always renders true
<?php
class Juice extends Liquid <
protected $apple ;
protected $orange ;
public function __get ( $name ) <
return $this -> $name ;
>
public function __construct ( $apple , $orange ) <
$this -> apple = $apple ;
$this -> orange = $orange ;
>
>

class Glass <
protected $liquid ;
public function __get ( $name ) <
return $name == «liquid» ? $this -> liquid : false ;
>
public function __construct () <
$this -> juice = new Juice ( 3 , 5 );
>
>

$glass = new Glass ();
var_dump (empty( $this -> liquid -> apple ));

/**
* The output is:
* bool(true)
*/
?>

The correct way is to force the evaluation of `__get()` first, by using extra braces around implicit statements like this:
<?php
var_dump (empty(( $this -> liquid -> apple )));

/**
* The output is:
* bool(false)
*/
?>

So if you are using packages that utilize object oriented designs and magic methods like `__get()`, it’s a good practice to always use double braces for `empty()` calls.

test if all multiarray’s are empty

<?php
function is_multiArrayEmpty ( $multiarray ) <
if( is_array ( $multiarray ) and !empty( $multiarray )) <
$tmp = array_shift ( $multiarray );
if(! is_multiArrayEmpty ( $multiarray ) or ! is_multiArrayEmpty ( $tmp )) <
return false ;
>
return true ;
>
if(empty( $multiarray )) <
return true ;
>
return false ;
>

$testCase = array (
0 => » ,
1 => «» ,
2 => null ,
3 => array(),
4 => array(array()),
5 => array(array(array(array(array())))),
6 => array(array(), array(), array(), array(), array()),
7 => array(array(array(), array()), array(array(array(array(array(array(), array())))))),
8 => array( null ),
9 => ‘not empty’ ,
10 => «not empty» ,
11 => array(array( «not empty» )),
12 => array(array(),array( «not empty» ),array(array()))
);

foreach ( $testCase as $key => $case ) <
echo » $key is_multiArrayEmpty keyword»>. is_multiArrayEmpty ( $case ). «<br>» ;
>
?>

OUTPUT:
========

0 is_multiArrayEmpty= 1
1 is_multiArrayEmpty= 1
2 is_multiArrayEmpty= 1
3 is_multiArrayEmpty= 1
4 is_multiArrayEmpty= 1
5 is_multiArrayEmpty= 1
6 is_multiArrayEmpty= 1
7 is_multiArrayEmpty= 1
8 is_multiArrayEmpty= 1
9 is_multiArrayEmpty=
10 is_multiArrayEmpty=
11 is_multiArrayEmpty=
12 is_multiArrayEmpty=

If you want to use empty() to evaluate an expression (not a variable), and you don’t have PHP 5.5+, you can do it by wrapping the call to empty in a function, like so:
<?php
function is_empty ( $var ) <

return empty( $var );

>
?>
Then you can do something like
<?php
if( is_empty ( NULL )) <
/* . */
>
?>
without issue, since the local variable $var is being tested rather than the expression in the function call itself.

In reply to «admin at ninthcircuit dot info»,

Using str_replace is unnecessary. I would encourage the use of trim which would most likely be faster (haven’t tested) and easier. Trim also takes care of other white space like line breaks and tabs. Actually, in most of the applications I code, I use a multi-dimensional array map function with trim on the Super Globals such as $_POST, $_GET and $_COOKIE as so far, there hasn’t been an instance where I would want any user input to begin or end with whitespace. The good thing about doing this is that you never have to worry about ‘trimming’ your input which makes your code easier and more reliable (incase you forget to trim some input).

Be careful about this :

For the verification of a form, to «block» entries such as a simple space or other, I thought of this combination:

function isEmpty($string) <
$val = preg_replace(‘#[^A-Za-z0-9]+#’, », $string) ;
$val = trim($string, »);
return ($string==») ;
>

This protects entries like: ‘ ‘ ,’ — ‘, ‘. — +’, . On entries like name, profession, . it’s helpful

Note that checking the existence of a subkey of an array when that subkey does not exist but the parent does and is a string will return false for empty.

<?php
$params = array( ‘search’ => ‘1’ );
empty( $params [ ‘search’ ][ ‘filter’ ]); # returns false
?>

This is correct, per the documentation (http://php.net/manual/en/language.types.string.php); quite a bit down the page is the Warning: «Writing to an out of range offset pads the string with spaces. Non-integer types are converted to integer.» ) I didn’t receive a warning but perhaps that’s correct too. depends on whether the string -> integer conversion is considered «illegal»: «Illegal offset type emits E_NOTICE.»

(i.e. since $params[‘search’] is a string, the ‘filter’ subscript is converted to 0, so the test becomes empty($params[‘search’][0]), which is obviously false), but it tripped me up enough to mistakenly file a bug report (which I’ve since closed).

empty() should not necessarily return the negation of the __isset() magic function result, if you set a data member to 0, isset() should return true and empty should also return true. A simpler implementation of the __isset magic function would be:

public function __isset($key) <
return isset($this-><$key>);
>

I don’t understand why this isn’t included in stdClass and inherited by default.

I can’t use empty() in all situations because ‘0’ is usually not considered empty to me. I did a quick benchmark over the most common ways of testing it. » == var suffers from » == 0 is true so that’s just there for curiosity.

<?php
$microtimeref = microtime ( true );
$a = 0 ;
$b = ‘asd’ ;
for ( $i = 0 ; $i < 5000000 ; $i ++)
<
if ( 0 == mb_strlen ( $b ))
<
$a ++;
>
>
echo «Total time 0 == mb_strlen(var): <b>» . round ( microtime ( true ) — $microtimeref , 3 ) . ‘s</b><br />’ ;
?>

The results:

Total time 0 == mb_strlen(var): 3.141s
Total time 0 === strlen(var): 2.904s
Total time 0 == strlen(var): 2.878s
Total time » == var: 1.774s
Total time » === var: 1.706s
Total time empty(var): 1.496s

Thus » === var will be my zero length string test.

David from CodeXplorer:
>> The ONLY reason to use empty() is for code readability. It is the same as an IF/ELSE check.
>> So, don’t bother using EMPTY in the real world.

Читать:
Неподдерживаемое 16 разрядное приложение windows 10 как исправить

This is NOT true. empty() will not generate warnings if you’re testing against an undefined variable as a simple boolean check will. On production systems, warnings are usually shut off, but they are often active on development systems.

You could test a flag with
<?php if ( $flagvar ) . ?>
but this can generate a warning if $flagvar is not set.

Instead of
<?php if (isset( $flagvar ) && $flagvar ) . ?>
you can simply use
<?php if (!empty( $flagvar )) . ?>

for easy readability without warnings.

I’m comparing behavior of `!` and `empty()`, find an undocumented behavior here.

just like cast-to-boolean, `empty()` cares about if SimpleXML object is made from emty tags.

How to check whether an array is empty using PHP?

players will either be empty or a comma separated list (or a single value). What is the easiest way to check if it’s empty? I’m assuming I can do so as soon as I fetch the $gameresult array into $gamerow ? In this case it would probably be more efficient to skip exploding the $playerlist if it’s empty, but for the sake of argument, how would I check if an array is empty as well?

24 Answers 24

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 you need to clean out empty values before checking (generally done to prevent explode ing weird strings):

Your Common Sense's user avatar

An empty array is falsey in PHP, so you don’t even need to use empty() as others have suggested.

PHP’s empty() determines if a variable doesn’t exist or has a falsey value (like array() , 0 , null , false , etc).

In most cases you just want to check !$emptyVar . Use empty($emptyVar) if the variable might not have been set AND you don’t wont to trigger an E_NOTICE ; IMO this is generally a bad idea.

Some decent answers, but just thought I’d expand a bit to explain more clearly when PHP determines if an array is empty.

An array with a key (or keys) will be determined as NOT empty by PHP.

As array values need keys to exist, having values or not in an array doesn’t determine if it’s empty, only if there are no keys (AND therefore no values).

So checking an array with empty() doesn’t simply tell you if you have values or not, it tells you if the array is empty, and keys are part of an array.

So consider how you are producing your array before deciding which checking method to use.
EG An array will have keys when a user submits your HTML form when each form field has an array name (ie name=»array[]» ).
A non empty array will be produced for each field as there will be auto incremented key values for each form field’s array.

Take these arrays for example:

If you echo out the array keys and values for the above arrays, you get the following:

ARRAY ONE:
[UserKeyA] => [UserValueA]
[UserKeyB] => [UserValueB]

ARRAY TWO:
[0] => [UserValue01]
[1] => [UserValue02]

ARRAY THREE:
[0] => []
[1] => []

And testing the above arrays with empty() returns the following results:

ARRAY ONE:
$ArrayOne is not empty

ARRAY TWO:
$ArrayTwo is not empty

ARRAY THREE:
$ArrayThree is not empty

An array will always be empty when you assign an array but don’t use it thereafter, such as:

This will be empty, ie PHP will return TRUE when using if empty() on the above.

So if your array has keys — either by eg a form’s input names or if you assign them manually (ie create an array with database column names as the keys but no values/data from the database), then the array will NOT be empty() .

In this case, you can loop the array in a foreach, testing if each key has a value. This is a good method if you need to run through the array anyway, perhaps checking the keys or sanitising data.

However it is not the best method if you simply need to know «if values exist» returns TRUE or FALSE. There are various methods to determine if an array has any values when it’s know it will have keys. A function or class might be the best approach, but as always it depends on your environment and exact requirements, as well as other things such as what you currently do with the array (if anything).

Here’s an approach which uses very little code to check if an array has values:

Using array_filter() :
Iterates over each value in the array passing them to the callback function. If the callback function returns true, the current value from array is returned into the result array. Array keys are preserved.

Running array_filter() on all three example arrays (created in the first code block in this answer) results in the following:

ARRAY ONE:
$arrayone is not empty

ARRAY TWO:
$arraytwo is not empty

ARRAY THREE:
$arraythree is empty

So when there are no values, whether there are keys or not, using array_filter() to create a new array and then check if the new array is empty shows if there were any values in the original array.
It is not ideal and a bit messy, but if you have a huge array and don’t need to loop through it for any other reason, then this is the simplest in terms of code needed.

I’m not experienced in checking overheads, but it would be good to know the differences between using array_filter() and foreach checking if a value is found.

Obviously benchmark would need to be on various parameters, on small and large arrays and when there are values and not etc.

James's user avatar

I ran the benchmark included at the end of the post. To compare the methods:

  • count($arr) == 0 : count
  • empty($arr) : empty
  • $arr == [] : comp
  • (bool) $arr : cast

and got the following results

The difference between empty and casting to a boolean are insignificant. I’ve run this test multiple times and they appear to be essentially equivalent. The contents of the arrays do not seem to play a significant role. The two produce the opposite results but the logical negation is barely enough to push casting to winning most of the time so I personally prefer empty for the sake of legibility in either case.

kaan_a's user avatar

If you’d like to exclude the false or empty rows (such as 0 => » ), where using empty() will fail, you can try:

array_filter() : If no callback is supplied, all entries of array equal to FALSE (see converting to boolean) will be removed.

If you’d like to remove all NULL, FALSE and empty strings ( » ), but leave zero values ( 0 ), you can use strlen as a callback, e.g.:

If you want to ascertain whether the variable you are testing is actually explicitly an empty array, you could use something like this:

Tim Ogilvy's user avatar

Why has no one said this answer:

Rob's user avatar

if you are to check the array content you may use:

Arun A S's user avatar

In my opinion the simplest way for an indexed array would be simply:

An ‘if’ condition on the array would evaluate to true if the array is not empty and false if the array is empty. This is not applicable to associative arrays.

PJately's user avatar

I use this code

But note that if the array has a large number of keys, this code will spend much time counting them, as compared to the other answers here.

Joseph Asir Raja's user avatar

I won’t repeat what has already been said here, just tested and the more efficient way on PHP-7.3 is !empty($myARR) or isset($myARR[0]) , both shows same speed. Anything else is pretty slower, including array_key_exists($myARR[0]) and just comparing $myARR !== Array() | $myARR !== [] . So, I prefer empty() , simple and fast.

You can use array_filter() which works great for all situations:

Making the most appropriate decision requires knowing the quality of your data and what processes are to follow.

  1. If you are going to disqualify/disregard/remove this row, then the earliest point of filtration should be in the mysql query.
  • WHERE players IS NOT NULL
  • WHERE players != »
  • WHERE COALESCE(players, ») != »
  • WHERE players IS NOT NULL AND players != »
  • . it kind of depends on your store data and there will be other ways, I’ll stop here.

If you aren’t 100% sure if the column will exist in the result set, then you should check that the column is declared. This will mean calling array_key_exists() , isset() , or empty() on the column. I am not going to bother delineating the differences here (there are other SO pages for that breakdown, here’s a start: 1, 2, 3). That said, if you aren’t in total control of the result set, then maybe you have over-indulged application "flexibility" and should rethink if the trouble of potentially accessing non-existent column data is worth it. Effectively, I am saying that you should never need to check if a column is declared — ergo you should never need empty() for this task. If anyone is arguing that empty() is more appropriate, then they are pushing their own personal opinion about expressiveness of scripting. If you find the condition in #5 below to be ambiguous, add an inline comment to your code — but I wouldn’t. The bottom line is that there is no programmatical advantage to making the function call.

Might your string value contain a 0 that you want to deem true/valid/non-empty? If so, then you only need to check if the column value has length.

Here is a Demo using strlen() . This will indicated whether or not the string will create meaningful array elements if exploded.

I think it is important to mention that by unconditionally exploding, you are GUARANTEED to generate a non-empty array. Here’s proof: Demo In other words, checking if the array is empty is completely useless — it will be non-empty every time.

If your string will NOT POSSIBLY contain a zero value (because, say, this is a csv consisting of ids which start from 1 and only increment), then if ($gamerow[‘players’]) < is all you need -- end of story.

. but wait, what are you doing after determining the emptiness of this value? If you have something down-script that is expecting $playerlist , but you are conditionally declaring that variable, then you risk using the previous row’s value or again generating Notices. So do you need to unconditionally declare $playerlist as something? If there are no truthy values in the string, does your application benefit from declaring an empty array? Chances are, the answer is yes. In this case, you can ensure that the variable is array-type by falling back to an empty array — this way it won’t matter if you feed that variable into a loop. The following conditional declarations are all equivalent.

How to Check Whether an Array Is Empty in PHP

Sometimes a software crash or other unexpected circumstances can occur because of an empty array. Hence, it is crucial to detect empty arrays beforehand and avoid them. This tutorial represents how to inspect whether a particular array is empty or not in PHP.

Let’s check out several useful means that will help you meet that goal.

Applying the empty() Function

The first method is applying the empty() function as shown in the example below:

The output of this code will indicate that the array is empty.

Applying the count() Function

The next function to use for detecting an empty array is the count() function. This function differs from the one above: it is aimed at counting the elements inside an array.

This function returns 0 once the array is empty. Otherwise, the number of elements will be returned. In the case below, the result is 0. Thus, the given array is empty:

Now, let’s see another example where the number of the elements is returned:

The output of this example is 4. It means that the array includes 4 elements.

Applying the sizeof() Function

The third method is using the sizeof() function. Globally, it is used for checking the array size. When its size is 0, then the array is considered empty. Otherwise, it’s not empty.

Похожие статьи