PHP: using empty () for an empty string?

I recently discovered this interesting article. Deceze .
> But I'm a little confused by one of the tips:

never use empty or isset for variables that must exist

Use is empty()not a good choice to check if it is $foo = '';empty?

+4
source share
3 answers

You cannot use empty(or isset) if you expect to exist $foo. This means that if, in accordance with your logic, the program $fooshould exist at the moment:

if ($foo === '')

Then do not follow these steps:

if (isset($foo))
if (empty($foo))

undefined. . , isset empty , PHP . :

$foo = $bar;
if (empty($føø)) ...

, true, $bar ? , undefined. , PHP :

if (!$føø) ...

: undefined føø on line...

, == false (!) empty .

, , . , $foo === '' strlen($foo) == 0 - , , , - .

+1

, , , , , . false, 0, null. - "".

. :

<?php

$string = null;
if (empty($string)) {
    echo "This is true";
}

$string = '';
if (empty($string)) {
    echo "This is true";
}

$string = 0;
if (empty($string)) {
    echo "This is true";
}

, , '':

<?php 

$string = '';
if (isset($string) && $string === '') {
    echo "This is true";
}

$string = null;
if (isset($string) && $string === '') {
    echo "This is false";
}
+5

PHP empty() .

:

  • blank

  • undefined null

, , empty() .

+2

Source: https://habr.com/ru/post/1661828/


All Articles