Skip to content

Instantly share code, notes, and snippets.

@JeffreyWay
Created July 28, 2012 19:09
Show Gist options
  • Save JeffreyWay/3194444 to your computer and use it in GitHub Desktop.
Save JeffreyWay/3194444 to your computer and use it in GitHub Desktop.
PHP: Set value if not exist

You know how, in JavaScript, we can set a value to a variable if one doesn't, like this:

name = name || 'joe';

This is quite common and very helpful. Another option is to do:

name || (name = 'joe');

Well, in PHP, that doesn't work. What many do is:

if ( empty($name) ) $name = 'joe';

Which works...but it's a bit verbose. My preference, at least for checking for empty strings, is:

$name = $name ?: 'joe';

What's your preference for setting values if they don't already exist?

@axelitus
Copy link

This all be over once PHP 7.4 arrives:

$name ??= 'joe';

@ben221199
Copy link

Does it throw warnings?

@ben221199
Copy link

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"

@str
Copy link

str commented May 24, 2023

Since PHP 7.4 we can now easily just say:

$name ??= 'joe';

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment