Por qué comprobar tanto isset() como!vaciar()


Hay una diferencia entre isset y !empty. Si hago esta doble comprobación booleana, ¿es correcta de esta manera o redundante? ¿y hay una manera más corta de hacer lo mismo?

isset($vars[1]) AND !empty($vars[1])
 232
php
Author: Dan Lugg, 2010-12-30

9 answers

Esto es completamente redundante. empty es más o menos la abreviatura de !isset($foo) || !$foo, y !empty es análoga a isset($foo) && $foo. Es decir, empty hace lo contrario de issetmás una verificación adicional para la truthiness de un valor.

O en otras palabras, empty es lo mismo que !$foo, pero no lanza advertencias si la variable no existe. Ese es el punto principal de esta función: hacer una comparación booleana sin preocuparse por la variable que se establece.

El manual pone es así:

empty() es lo contrario de (boolean) var, excepto que no se genera ninguna advertencia cuando la variable no está establecida.

Simplemente puede usar !empty($vars[1]) aquí.

 367
Author: deceze,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-01-01 02:11:46

isset() prueba si se establece una variable y no null:

Http://us.php.net/manual/en/function.isset.php

empty() puede devolver true cuando la variable se establece en ciertos valores:

Http://us.php.net/manual/en/function.empty.php

Para demostrar esto, pruebe el siguiente código con un the_var unassigned, establecido en 0 y establecido en 1.

<?php

#$the_var = 0;

if (isset($the_var)) {
  echo "set";
} else {
  echo "not set";
}

echo "\n";

if (empty($the_var)) {
  echo "empty";
} else {
  echo "not empty";
}
?>
 28
Author: GreenMatt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-20 22:35:42

La respuesta aceptada no es correcta.

Isset() es NO equivalente a !vaciar().

Creará algunos errores bastante desagradables y difíciles de depurar si sigue esta ruta. por ejemplo, intente ejecutar este código:

<?php

$s = '';

print "isset: '" . isset($s) . "'. ";
print "!empty: '" . !empty($s) . "'";

?>

Https://3v4l.org/J4nBb

 12
Author: Snowcrash,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-18 11:38:54
$a = 0;
if (isset($a)) { //$a is set because it has some value ,eg:0
    echo '$a has value';
}
if (!empty($a)) { //$a is empty because it has value 0
    echo '$a is not empty';
} else {
    echo '$a is empty';
}
 8
Author: rajmohan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-29 03:37:59

Empty just check is the refered variable / array has an value if you check the php doc (empty) you'll see this things are considered emtpy

* "" (an empty string)
* 0 (0 as an integer)
* "0" (0 as a string)
* NULL
* FALSE
* array() (an empty array)
* var $var; (a variable declared, but without a value in a class)

While isset comprobar si la variable isset y not null que también se puede encontrar en el php doc (isset)

 3
Author: Breezer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-12-30 04:12:29

"Empty": solo funciona en variables. Vacío puede significar diferentes cosas para diferentes tipos de variables (comprobar manual: http://php.net/manual/en/function.empty.php).

"isset": comprueba si la variable existe y busca un valor true NULL o false. Puede desactivarse llamando a "desactivado". Una vez más, revise el manual.

El uso de cualquiera de los dos depende del tipo de variable que esté utilizando.

Yo diría, es más seguro comprobar ambos, porque usted está comprobando en primer lugar si la variable existe, y si no es realmente NULA o vacía.

 0
Author: szahn,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-12-30 04:18:11

Si usamos la misma página para agregar / editar a través del botón enviar como abajo

<input type="hidden" value="<?echo $_GET['edit_id'];?>" name="edit_id">

Entonces no debemos usar

isset($_POST['edit_id'])

Bcoz edit_id se establece todo el tiempo si se trata de agregar o editar página, en su lugar debemos usar check below condition

!empty($_POST['edit_id'])
 0
Author: diEcho,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-12-30 07:12:59

No es necesario.

No se genera ninguna advertencia si la variable no existe. Eso significa empty() es esencialmente el equivalente conciso a !isset (var var) / / var var == falso.

Php.net

 0
Author: madlopt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-04 08:50:30
  • Del sitio web PHP, refiriéndose a la función empty():

Devuelve FALSE si var tiene un valor no vacío y distinto de cero.

Eso es algo bueno de saber. En otras palabras, todo desde NULL, a 0 a "" devolverá TRUE cuando se use la función empty().

  • Aquí está la descripción de lo que devuelve la función isset():

Devuelve TRUE si var existe; FALSE de lo contrario.

En otras palabras, solo las variables que no exist (o, las variables con valores estrictamente NULL) devolverán FALSE en la función isset(). Todas las variables que tienen cualquier tipo de valor, ya sea 0, una cadena de texto en blanco, etc. volverá TRUE.

 0
Author: Ende,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-08 08:00:00