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?

@RodrigoEspinosa
Copy link

I think the best way is: $name = (isset($name)) ? $name : "joe"; very similar to name || (name = 'joe');

@banago
Copy link

banago commented Aug 5, 2012

Jeffrey, guess what, you can do the same thing on PHP:

$myValue = $someOtherValue ?: true;

http://www.selfcontained.us/2010/11/30/php-coalesce/

@Krknv
Copy link

Krknv commented Jan 16, 2015

$item = isset($arr["super_long_key_name"]) ? $arr["super_long_key_name"] : "default";
$item =@ $arr["super_long_key_name"]) ?: "default";

@agaezcode
Copy link

php Echo number if the number is not zero.

$number ?: $number != '0'

@fvzsf65536
Copy link

isset($name) || $name = 'Joe';

or

!empty($name) || $name = 'Joe';

@fvzsf65536
Copy link

PHP7:

$name = $name ?? 'Joe';

@waspinator
Copy link

How would you do it in an array?

$name = []

$new_array = [
     'first_name' => $name['first'] ?? 'Joe'
]

@3642066
Copy link

3642066 commented Jan 1, 2016

I just used : if ( empty($name) ) $name = 'joe';
This is more a kind of "human readable", for me .
I used for setting the opacity of a php image processing app, so i can update the main app later, because i'm using a slider input on app test version but i still using the same URL for processing the images, with caused bug because of a missing variable (opacity) .
Thank you .

@eness
Copy link

eness commented May 4, 2016

Here is the perfect solution I've found and been using for a while ..

$name = 'John';
echo $name ?: 'User has no name';
// result : John

This will print John if $name is not empty but if $name is empty, it will print out 'User has no name' instead, which acts like a default value.

$name = ''; // or $name = null;
echo $name ?: 'User has no name';
result : User has no name

@nwpray
Copy link

nwpray commented Aug 15, 2016

Best way is always the ternary operators. Sorry to open this up again, but I spent a good 20 min testing out cases because this conversation did so many loops through multiple techniques but didn't appear to settle.

The form:

{var} = {case} ? {val} : {default};

and an example:

$values = [ 'test' => 'testing' ];
$target_val = isset($values['test']) ? $values['test'] : null;

I settled on this because it appeared to be the most versatile. You can set a default value and if your using a false evaluating value as the default its easy to see if the variable was set. a.k.a. in this example if I do:

if(!$target_val)
{
   echo 'not set'; 
}

I know that the value is not set and if I want to check if it is set:

if(!!$target_val)
{
   echo 'set';
}

And it may be a bit verbose but you can do it all in one swoop like this:

if(!($target_val = isset($values['test']) ? $values['test'] : null))
{
   //Is not set case
}
//Continue normally because you know its set

And like has been said, you can shorthand the ternary and just use:

$target_val = $values['test'] ?: null;

But you will get a notice thrown on array value not set so I always just use isset and assign a value in the ternary to avoid silencing messages for no reason.

@RedSparr0w
Copy link

RedSparr0w commented Sep 12, 2017

I know this is a very old thread but,

with php 7+ you can use something like the following:

$user = $user ?? "" ?: "User not set";
$user assigned as $user will return
undefined User not set
"" User not set
null User not set
false User not set
"John" John

?? checks if the value is undefined or null
?: checks if the value is null or false or an empty string

@robrecord
Copy link

robrecord commented Oct 9, 2018

RedSparr0w you can shorten this:

$user ?? $user = "User not set";

@sobujbd
Copy link

sobujbd commented Jun 4, 2019

Finally, I prefer...

/**
 * @param $value
 * @param $default
 * @return mixed
 */
function get_string($value, $default)
{
    if (!empty($value)) {
        return $value;
    } else {
        return $default;
    }
}

Usages: get_string($name, "Unknown");

@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