Php как проверить переменную на пустоту
У нас будет несколько переменных, которые будут иметь разное значение ив том числе будут пустыми, не существовать, либо иметь внутри пробел.
Переменные для проверки на пустоту в php
Если — $primer не существует.
Если $primer =»Здесь есть текст»;
Перечислим все проверки, которые будут проходить переменные на пустоту в том числе :
Первым -> мы получим var_dump переменной, тип и значение — это самый надежный способ узнать, что же внутри перменной!
isset -> определяет, установлена ли переменная
empty -> Проверяет, пуста ли переменная
if($primer)-> если переменная, часто употребляемая проверка
if(trim($primer))-> тоже самое, что и предыдущий пункт, только добавим «trim»
if($primer == false)-> если переменная равна false по значению
if($primer === false)-> если переменная равна false по значению и по типу
if($primer == true)-> если переменная равна true по значению
if($primer === true)-> если переменная равна true по значению и по типу
Проверим переменную если она ничему не равна
В первом пункте, с жими проверками на пустоту, разложим все по пунктам и сделаем вывод, что это значит. Для остальных путов, приведем только результат!
Первая по списку, это переменная, которую можно назвать пустой. Которая равна «ничему».
Результаты проверок, на пустоту, если в переменной ничего нет
Проверка на пустоту переменной если она равна пробелу
Тест проверки переменной на пустоту, если в ней есть пробел
переменная не пустая empty
переменная не пустая is primer
переменная не пустая false
переменная не пустая false2
переменная не пустая true
Вывод из теста на проверку переменной с пробелом :
Только вариант 5 после проверки переменной на пустоту, говорит, что там действительно пустота!
А как же вариант 9 -> true по значению, но false по типу(т.е. там, на самом деле должно было быть написано, что переменная с пробелом это не true )
Проверить на пустоту, если переменная не существуют
Следующий тест проверки на пустоту -> если переменная не существует!
переменная не существует isset
переменная не пустая false2
Вывод теста проверки на пустоту отсутствующей переменной
Здесь, как говорится не нужно слов! Тест проверки на пустоту сработал как и ожидалось, кроме строки №7 -> этот пункт перекликается с поведением c true в предыдущем пункте(строка №9) -> зеркальная ситуация.
Проверим на пустоту переменную, если она существует!
И для нашего успокоения давайте проверим на пустоту, если в переменная не пустая -> пусть это будет текст:
string(30) «Здесь есть текст» var_dump
переменная не пустая empty
переменная не пустая is primer
переменная не пустая trim
переменная не пустая false
переменная не пустая false2
переменная не пустая true
Вывод о результатах проверки если переменная не пустая:
Можно было столько проверок не делать — но мне, самому было интересно. что возвратит каждая проверка.
Что же касается проверки на пустоту, то самое правильное на мой взгляд это вариант
if(trim($primer))<> В данном случае: Эту конструкцию можно прочитать — если переменная не пустая. то -> действие
empty
Проверяет, считается ли переменная пустой. Переменная считается пустой, если она не существует или её значение равно false . empty() не генерирует предупреждение, если переменная не существует.
Список параметров
Если переменная не существует, предупреждение не генерируется. Это значит, что empty() фактически является точным эквивалентом конструкции !isset($var) || $var == false
Возвращаемые значения
Возвращает true , если параметр var не существует, если значение равно нулю, либо не задано, смотрите Преобразование в булев тип. В противном случае возвращает false .
Примеры
Пример #1 Простое сравнение empty() и isset() .
// Принимает значение true, потому что $var пусто
if (empty( $var )) <
echo ‘$var или 0, или пусто, или вообще не определена’ ;
>
// Принимает значение true, потому что $var определена
if (isset( $var )) <
echo ‘$var определена, даже если она пустая’ ;
>
?>
Пример #2 empty() и строковые индексы
Результат выполнения данного примера:
Примечания
Замечание: Поскольку это языковая конструкция, а не функция, она не может вызываться при помощи переменных функций или именованных аргументов.
Замечание:
При использовании функции empty() на недоступных (необъявленных) свойствах объекта будет вызван встроенный метод объекта __isset(), если он определён.
Смотрите также
- isset() — Определяет, была ли установлена переменная значением, отличным от null
- unset() — Удаляет переменную
- array_key_exists() — Проверяет, присутствует ли в массиве указанный ключ или индекс
- count() — Подсчитывает количество элементов массива или Countable объекте
- strlen() — Возвращает длину строки
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.
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.
(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.
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.
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.
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=
empty
Проверяет, считается ли переменная пустой. Переменная считается пустой, если она не существует или её значение равно FALSE . empty() не генерирует предупреждение если переменная не существует.
Список параметров
Замечание:
До PHP 5.5 empty() проверяет только переменные, и попытка проверить что-то еще вызовет ошибку синтаксиса. Другими словами, следующий код не будет работать: empty(trim($name)). Используйте вместо него trim($name) == false.
Если переменная не существует, предупреждение не генерируется. Это значит, что empty() фактически является точным эквивалентом конструкции !isset($var) || $var == false
Возвращаемые значения
Возвращает FALSE , если var существует, и содержит непустое и ненулевое значение. В противном случае возвращает TRUE .
- "" (пустая строка)
- 0 (целое число)
- 0.0 (дробное число)
- "0" (строка)
- NULL
- FALSE
- array() (пустой массив)
- $var; (переменная объявлена, но не имеет значения)
Список изменений
empty() теперь поддерживает выражения, а не только переменные.
Проверка нечислового индекса строки возвращает TRUE .
Примеры
Пример #1 Простое сравнение empty() и isset() .
// Принимает значение true, потому что $var пусто
if (empty( $var )) <
echo ‘$var или 0, или пусто, или вообще не определена’ ;
>
// Принимает значение true, потому что $var определена
if (isset( $var )) <
echo ‘$var определена, даже если она пустая’ ;
>
?>
Пример #2 empty() и строковые индексы
В PHP 5.4 был изменен способ обработки строковых индексов в empty() .
check if variable empty
If you want to test whether a variable is really NULL , use the identity operator:
If you want to check whether a variable is not set:
Or if the variable is not empty, an empty string, zero, .
If you want to test whether a variable is not an empty string, ! will also be sufficient:
You can check if it’s not set (or empty) in a number of ways.
You can check if it’s declared with:
Take note that PHP interprets 0 (integer) and «» (empty string) and false as «empty» — and dispite being different types, these specific values are by PHP considered the same. It doesn’t matter if $var is never set/declared or if it’s declared as $var = 0 or $var = «». So often you compare by using the === operator which compares with respect to data type. If $var is 0 (integer), $var == «» or $var == false will validate, but $var === «» or $var === false will not.
here i have explained how the empty function and isset works please use the one that is appropriate also you can use is_null function also
empty() is a little shorter, as an alternative to checking !$user_id as suggested elsewhere:
To check for null values you can use is_null() as is demonstrated below.
![]()
Please define what you mean by «empty».
The test I normally use is isset() .
you can use isset() routine .
also additionaly you can refer an range of is_type () functions like
is_string(), is_float(),is_int() etc to further specificaly test
2 . No. I actually did not understand why you write such a construct.
3 . Put all values into array, for example $ar[«user_id»], etc.
![]()
![]()
Its worth noting — and I only found this out after nearly 9 years of PHP coding that the best way of checking any variable exists is using the empty() function. This is because it doesn’t generate errors and even though you turn them off — PHP still generates them! empty() however won’t return errors if the variable doesn’t exist. So I believe the correct answer is not to check if its null but to do the following
Note the PHP manual
variable is considered empty if it does not exist or if its value equals FALSE