Hans Wittwer

Geschichten, die das Leben schrieb

Hinweise

PHP empty vs. isset vs. is_null vs. if

🏁

Was ist in PHP der Unterschied zwischen empty(var), isset(var), is_null(var) und if(var)?

Definition von $x var_dump($x); empty($x) isset($x) is_null($x) if($x)
$x nicht definiert NULL bool(true) bool(false) bool(true) Nein
$x = null NULL bool(true) bool(false) bool(true) Nein
$x = 0 int(0) bool(true) bool(true) bool(false) Nein
$x = "0" string(1) "0" bool(true) bool(true) bool(false) Nein
$x = 2 int(2) bool(false) bool(true) bool(false) Ja
$x = 2.5 float(2.5) bool(false) bool(true) bool(false) Ja
$x = "2" string(1) "2" bool(false) bool(true) bool(false) Ja
$x = "2.5" string(3) "2.5" bool(false) bool(true) bool(false) Ja
$x = "" string(0) "" bool(true) bool(true) bool(false) Nein
$x = "Ueli" string(4) "Ueli" bool(false) bool(true) bool(false) Ja
$x = array() array(0) { } bool(true) bool(true) bool(false) Nein
$x = ["Ueli"] array(1)
{ [0]=> string(4) "Ueli" }
bool(false) bool(true) bool(false) Ja
$x = [
"Vorname" => "Ueli",
"Nachname" => "Müller"
];
array(2)
{
["Vorname"]=> string(4) "Ueli",
["Nachname"]=> string(7) "Müller"
}
bool(false) bool(true) bool(false) Ja
Hinweis zur Spalte if($x):

if($x) {
   echo "Ja";
} else {
   echo "Nein";
}


if($x) entspricht if(! empty($x)) und i s_null() ist das Umgekehrte von isset(). Das Sprachkonstrukt echo $x; nur verwenden, wenn isset() true meldet und der Datentyp string, int oder float ist, sonst wirft PHP einen Fehler. Die Funktion empty() meldet bei NA, NULL, 0, "" und array(0) true. Die Funktion isset() meldet nur bei NA und NULL false.

Zurück zum Inhaltsverzeichnis