Hans Wittwer

Geschichten, die das Leben schrieb

Serverseitige Skriptsprache PHP

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)
Hinweis zur Spalte if($x):

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


if($x) entspricht if(! empty($x)) und is_null() ist das Umgekehrte von isset().
$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" string(1) "2" 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
Den Befehl echo nur verwenden, wenn isset() true meldet, sonst wirft PHP einen Fehler.
Die Funktion empty() meldet bei NA, NULL, 0, "" und array(0) true.
Die Finktion isset() meldet nur bei NA und NULL false.

Zurück zum Inhaltsverzeichnis