PHP Set Value If Not Exists

Various ways to set value if the value does not exist in PHP.

The whole discussion summarized nicely at the end by @ben221199:

This code:

<?php
error_reporting(E_ALL);
ini_set("display_errors",1);

echo("PHP Variable Init");

if ( empty($A) ) $A = 'joe';
var_dump($A);

$B = $B ?: 'joe';
var_dump($B);

if (!isset($C)) $C = 'joe';
var_dump($C);

isset($D) OR $D = 'joe';
var_dump($D);

$E = (isset($E))?$E:'joe';
var_dump($E);

!isset($F) && $F = 'joe';
var_dump($F);

$G || ($G = 'joe');
var_dump($G);
?>

Will generate this:

string(3) "joe"
<br /><b>Notice</b>:  Undefined variable: B in <b>/home/webben/domains/yocto.nu/private_html/projects/phpvarinit/index.php</b> on line <b>10</b><br />
string(3) "joe"
string(3) "joe"
string(3) "joe"
string(3) "joe"
string(3) "joe"
<br /><b>Notice</b>:  Undefined variable: G in <b>/home/webben/domains/yocto.nu/private_html/projects/phpvarinit/index.php</b> on line <b>25</b><br />
string(3) "joe"

Leave a Comment