Перейти к содержимому

Как проверить массив на пустоту

  • автор:

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 36 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.

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.

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
?>

(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.

What Is the Best Way to Check if an Array Is Empty or Not in JavaScript?

The best way to check if an array is empty in JavaScript is by using the Array.isArray() method (ES5+) and array’s length property together like so:

Similarly, using else , or the inverse would check if the array is not empty. For example:

The Array.isArray method is a part of ES5 specification, and has a very good browser support. However, if the browsers you’re targeting lack the support, you can use a polyfill.

To understand why there’s a need to use both Array.isArray() and array.length , let’s examine the two in detail:

Using Array.isArray() Method

In the first part of the if condition we check if the variable value is indeed an array to rule out all other types of values. Array.isArray() returns true for the following:

On the flipside, the method returns false for the following:

Why Not Use typeof Instead of Array.isArray() ?

Simply because an array in JavaScript is an instance of the Array object and typeof would return the type object for it. To illustrate this, consider the following example:

Why Not Use instanceof Instead of Array.isArray() ?

Array.isArray() is preferred over instanceof because it works through multiple contexts (such as frames or windows) correctly whereas instanceof does not. The reason for this is the fact that in JavaScript each window or frame has its own execution environment and a different scope. This means, for example, if a script passes an object from one context to another via functions, it may lead to unexpected results. To demonstrate this, let’s consider the following examples:

From the examples above you can see that instanceof returns false when checking objects from different contexts. This happens because the instanceof operator works by checking if Array.prototype is on an object’s [[Prototype]] chain. Since, the Array constructor used for creating the object instance is from a different environment compared to the one used for the test, instanceof returns false .

In the context of our example, this means that iframeArrayObj ‘s prototype is the Array.prototype in the iframe window, and not the Array.prototype in the window where the code is run from; basically, Array.prototype !== window.frames[0].Array .

Considering all that, it is best to simply use Array.isArray() , especially when creating a framework, library or a plugin, where the environment in which it will be used is not known in advance.

Using the length Property

In the second part of the if statement we check if the array has any elements. Since, 0 is a falsy value in JavaScript, the if condition will fail if the length is zero. Conversely, if the length is not zero the condition will succeed, because non-zero numbers in JavaScript are considered truthy.

Why Not Just Use the length Property on Its Own?

The reason the length property is not used on its own is because length can apply to different types of values in JavaScript and be valid. Therefore, it is important to rule out all values that are not an array first.

Hope you found this post useful. It was published 10 Jan, 2020 (and was last revised 07 Feb, 2021 ). Please show your love and support by sharing this post.

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

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

Arun A S's user avatar

Why has no one said this answer:

Rob'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 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.

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

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.

Как проверить массив на пустоту?

Оказалось это не работает.
С ARRAY[0]= работает. Но стоит пявиться ARRAY[1]= и всё.

Как же проверить за один раз, пустой ли массив?
Столько скриптов переписано, а этого не знаю, вернее, был уверен, что знаю, а оказалось вон оно как.
Должно же быть какое-то элементарное решение.

$ <#array[@]>— возвращает длину массива

еще $ преобразует массив в строку, тогда возможно -z сработает.

Мне не количество элементов узнать нужно, а проверить, что все элементы пустые, т.е. что они ARRAY[0]= ARRAY[1]= ARRAY[2]= . , а не ARRAY[0]=iuy4tv8q ARRAY[1]=’ ‘ ARRAY[2]=1

тоже не работает

А вобще, пустой массив и массив из пустых элементов это разные вещи.

Я поигрался, вроде работает:

работает, но какое-то не очевидное решение

Это чисто теоретический вопрос или практический?

Если практический, и если откуда-то сверху нет требования делать именно шелл-скриптами, рекомендую посмотреть в сторону чего-то более развитого, хотя бы питон/пхп, ибо шелл-скрипт с такой логикой ты даже если и напишешь то будет сложноподдерживаемым.

Столько скриптов переписано, а этого не знаю, вернее, был уверен, что знаю, а оказалось вон оно как.

Это и есть главная проблема помойки под названием bash (и другие shеллов тоже касается по большей части). На этом невозможно нормально программировать, нет нормального синтаксиса, куча edge кейсов, старое легаси, да и язык построен так, чтобы интерпретатору было удобно, а не человеку

Использовать какие-то структуры данных на баше это боль, и как только они появляются в коде, проще сразу все переписать все на питон. Единственный плюс баша это возможность быстро строить пайплайны и вызывать экзешники, без всякой сторонней мишуры как в том же пайтоне.

Не, можно конечно постичь все тонкости, знать все подводные камни, но один вопрос: зачем на это тратить свое время?

Использовать какие-то структуры данных на баше это боль, и как только они появляются в коде, проще сразу все переписать все на питон. Единственный плюс баша это возможность быстро строить пайплайны и вызывать экзешники, без всякой сторонней мишуры как в том же пайтоне.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Школа онлайн с государственным аттестатом