Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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?

@oyatek

This comment has been minimized.

Copy link

@oyatek oyatek commented Jul 28, 2012

last way always

@inf0rmer

This comment has been minimized.

Copy link

@inf0rmer inf0rmer commented Jul 28, 2012

Doesn't empty() check for empty strings ("")? I always use

if (!isset($name)) $name = 'joe';
@philipptempel

This comment has been minimized.

Copy link

@philipptempel philipptempel commented Jul 28, 2012

isset($name) OR $name = 'joe';

works however only with PHP >= 5.x (maybe even 5.3, I'm not quite sure right now)

@JeffreyWay

This comment has been minimized.

Copy link
Owner Author

@JeffreyWay JeffreyWay commented Jul 28, 2012

empty() refers to lots of different things, including false, empty string, empty array, null, etc. You can certainly use both. :)

http://php.net/empty

@zecho

This comment has been minimized.

Copy link

@zecho zecho commented Jul 28, 2012

but the last generates a notice

@JeffreyWay

This comment has been minimized.

Copy link
Owner Author

@JeffreyWay JeffreyWay commented Jul 28, 2012

Yeah - that assumes that the variable isset, but may be an empty string.

@zecho

This comment has been minimized.

Copy link

@zecho zecho commented Jul 28, 2012

error_reporting(E_ALL);

Notice: Undefined variable: name in test.php on line 2

@everzet

This comment has been minimized.

Copy link

@everzet everzet commented Jul 28, 2012

Alternative to

$name || ($name = 'joe');

In php is:

<?php
isset($name) || $name = 'joe';

It's a good way to set value if you're not sure, that variable is defined.
Otherwise, second way is a better option:

name = name || 'joe';
<?php
$name = $name ?: 'joe';
@inf0rmer

This comment has been minimized.

Copy link

@inf0rmer inf0rmer commented Jul 28, 2012

Yeah, that's why I'm weary of using empty() to check if something is assigned... false can be a perfectly valid value.

@kamaln7

This comment has been minimized.

Copy link

@kamaln7 kamaln7 commented Jul 28, 2012

Wouldn't the last one throw a warning?

@JeffreyWay

This comment has been minimized.

Copy link
Owner Author

@JeffreyWay JeffreyWay commented Jul 28, 2012

Ahh - yeah good point.

@zecho

This comment has been minimized.

Copy link

@zecho zecho commented Jul 28, 2012

maybe

isset($name) or $name = 'xxx';

is really the best current solution. Also you can use more complex checks for the variable like:

isset($name) && $name == 3 or $name = 'xxx';

Using the operator precedence 'or' will be checked last.

@josephilipraja

This comment has been minimized.

Copy link

@josephilipraja josephilipraja commented Jul 28, 2012

I use
$name = (isset($name))?$name:'joe';

@kamaln7

This comment has been minimized.

Copy link

@kamaln7 kamaln7 commented Jul 28, 2012

I use

<?php
!isset($name) && $name = 'joe';
@JeffreyWay

This comment has been minimized.

Copy link
Owner Author

@JeffreyWay JeffreyWay commented Jul 28, 2012

@zecho - Accept that $name will only be xxx if the variable doesn't exist. If it's set to an empty string, it won't change.

@everzet

This comment has been minimized.

Copy link

@everzet everzet commented Jul 28, 2012

@zecho your example will do quite opposite of

$name || ($name = 'joe');

will override value if $name is defined and will do nothing otherways.

@kamaln7

This comment has been minimized.

Copy link

@kamaln7 kamaln7 commented Jul 28, 2012

@everzet: "Also, isset() will throw an exception for undefined variables."
It does not, (http://php.net/isset) "Returns TRUE if var exists and has value other than NULL, FALSE otherwise."

@zecho

This comment has been minimized.

Copy link

@zecho zecho commented Jul 28, 2012

@everzet, it's not true.

isset($name) && $name == 3 or $name = 'xxx';                                                                                                           
echo $name, "\n";                                                                                                                                      
isset($name) or $name = 'yyy';                                                                                                                         
echo $name, "\n";                                                                                                                                      

gives this:

xxx
xxx
@everzet

This comment has been minimized.

Copy link

@everzet everzet commented Jul 28, 2012

@kamaln7 yep, my mistake :)

@RamyTalal

This comment has been minimized.

Copy link

@RamyTalal RamyTalal commented Jul 28, 2012

I think this is more readable:

<?php $name = empty($name) and $name = 'joe';
@kamaln7

This comment has been minimized.

Copy link

@kamaln7 kamaln7 commented Jul 28, 2012

@RamyTalal: It is ;)

@brockb

This comment has been minimized.

Copy link

@brockb brockb commented Jul 28, 2012

Like others... that last one throws a warning so I use:

$name = $name ? $name : 'joe';

@everzet

This comment has been minimized.

Copy link

@everzet everzet commented Jul 28, 2012

@zecho ok, you're right :) My bad. Note to myself: never ever argue with someone when you're sleepy :D

@JeffreyWay

This comment has been minimized.

Copy link
Owner Author

@JeffreyWay JeffreyWay commented Jul 28, 2012

@kevbradwick

This comment has been minimized.

Copy link

@kevbradwick kevbradwick commented Jul 28, 2012

Depends on context. Generally, if inside of a class method or standard function, I know what variables are set because of the parameter signature. If I have to use the php extract() method to turn array key => val to variables, I'll merge the input array with defaults so I know what variable will be set inside the scope it is used.

Generally, if I don't know what variables are set, I'll look at how I can refactor my code to make it more solid - and of course, unit test!

@everzet

This comment has been minimized.

Copy link

@everzet everzet commented Jul 28, 2012

@kevbradwick can't agree more here. And in case, where var is defined and you just need to provide default value in case of null, $var = $var ?: 'default' is the best and cleanest option IMO.

@everzet

This comment has been minimized.

Copy link

@everzet everzet commented Jul 28, 2012

@JeffreyWay why not using null as default argument? IMO, it will be much more logical than $name = ''.

@zecho

This comment has been minimized.

Copy link

@zecho zecho commented Jul 28, 2012

@everzet, sorry but again I can't agree with you :)

$xx = null; 
isset($xx); //false
@kevbradwick

This comment has been minimized.

Copy link

@kevbradwick kevbradwick commented Jul 28, 2012

@JeffreyWay In your use case I would probably do the following;

function example($name='') {
    $name = (string) $name;
    if (strlen($name) > 0) {
        return $name . "\n";
    }
    return "jeff\n";
}

But I always prefer more verbose code - just a preference!

@gabrielcastillo

This comment has been minimized.

Copy link

@gabrielcastillo gabrielcastillo commented Jul 28, 2012

if(!isset($name)){ $name = 'joe'}

@isimmons

This comment has been minimized.

Copy link

@isimmons isimmons commented Jul 28, 2012

@JeffreyWay I like the last option as long as the var has a default set like in your example function to avoid the undefined variable message. Or shorten it to one line by doing it this way.

return $name ? $name : 'joe';

If the variable isn't set to '' by default it doesn't seem like there would be a way around using isset() to avoid the warning.

@avinashz

This comment has been minimized.

Copy link

@avinashz avinashz commented Jul 29, 2012

if(!isset($name)){ $name = 'joe'}

@everzet

This comment has been minimized.

Copy link

@everzet everzet commented Jul 29, 2012

@zecho well, in case of default argument with = null, you don't need isset(...) check - you just need $name = $name ?: 'default'. I was talking bout that.

@zecho

This comment has been minimized.

Copy link

@zecho zecho commented Jul 30, 2012

@everzet, you're not right again. When $var === null your statement generates notice 'Undefined variable' because doesn't make difference between null and undefined.

@everzet

This comment has been minimized.

Copy link

@everzet everzet commented Jul 30, 2012

@zecho nope, here i'm absolutely right:

<?php

function printName($name = null) {
  $name = $name ?: 'default';

  echo $name."\n";
}

printName();
printName('test');

will output:

default
test

$var === null means that variable is defined (its value is null).

@zecho

This comment has been minimized.

Copy link

@zecho zecho commented Jul 30, 2012

try with:

error_reporting(E_ALL);
ini_set('display_errors', 1);

also:

$var = null;
echo isset($var);
@everzet

This comment has been minimized.

Copy link

@everzet everzet commented Jul 30, 2012

@zecho no, you try. No exceptions/notices/errors for me :)

<?php

error_reporting(E_ALL);
ini_set('display_errors', 1);

function printName($name = null) {
  $name = $name ?: 'default';

  echo $name."\n";
}

printName();
printName('test');
@zecho

This comment has been minimized.

Copy link

@zecho zecho commented Jul 30, 2012

do this outside a function/method. I won't explain you what's the difference in php between function parameter and a variable. Also put as first line in the function

echo (int)isset($name);

to see the result when $name = null

@everzet

This comment has been minimized.

Copy link

@everzet everzet commented Jul 30, 2012

@zecho

<?php

error_reporting(E_ALL);
ini_set('display_errors', 1);

$name = null;
var_dump(isset($name));

$name = $name ?: 'default';

echo $name."\n";
var_dump(isset($name));
bool(false)
default
bool(true)

I don't get what you're trying to prove here, but please, explain me the difference in php between function parameter and variable.

@everzet

This comment has been minimized.

Copy link

@everzet everzet commented Jul 30, 2012

@zecho also, i think you've started arguing about https://gist.github.com/3194444#gistcomment-381958 Please re-read it again, cuz it looks like we have misunderstanding here.

@zecho

This comment has been minimized.

Copy link

@zecho zecho commented Jul 30, 2012

@everzet, sorry about misunderstanding, I didn't read properly this comment. The idea is that you can't use $name = $name ?: 'default' when variable is not initialized at all (even with $name = null ).

@everzet

This comment has been minimized.

Copy link

@everzet everzet commented Jul 30, 2012

@zecho yep, and here is the source misunderstanding:

... even with $name = null

$name = null initializes variable. With null value.

In

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

$name = null;
var_dump($name);

var_dump($name); is a proper statement and will return:

NULL

Without any exception/notice. And

<?php

error_reporting(E_ALL);
ini_set('display_errors', 1);

$name = null;
$name = $name ?: 'default';

echo $name;

Will successfully output

default

Without any exception/notice. Because null is a proper value of any variable.

@avioli

This comment has been minimized.

Copy link

@avioli avioli commented Jul 31, 2012

Just my 20 cents - null initialises the variable with nothing. It prepares the variable to be garbage collected in the next cycle.
It only does the following - puts it in the current scope so the interpreter is not considering it not existing. It's similar to what global $global_var; does.

var_dump( isset( $null_var ) ); will output bool(false) anyway.

Setting a variable to null is only useful for cases as with the one you circle around @everzet - having it as a function's default variable.

@RodrigoEspinosa

This comment has been minimized.

Copy link

@RodrigoEspinosa RodrigoEspinosa commented Aug 1, 2012

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

@banago

This comment has been minimized.

Copy link

@banago 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

This comment has been minimized.

Copy link

@Krknv 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

This comment has been minimized.

Copy link

@agaezcode agaezcode commented Mar 6, 2015

php Echo number if the number is not zero.

$number ?: $number != '0'
@fvzsf65536

This comment has been minimized.

Copy link

@fvzsf65536 fvzsf65536 commented May 4, 2015

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

or

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

@fvzsf65536

This comment has been minimized.

Copy link

@fvzsf65536 fvzsf65536 commented May 7, 2015

PHP7:

$name = $name ?? 'Joe';

@waspinator

This comment has been minimized.

Copy link

@waspinator waspinator commented Oct 6, 2015

How would you do it in an array?

$name = []

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

This comment has been minimized.

Copy link

@3642066 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

This comment has been minimized.

Copy link

@eness 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

This comment has been minimized.

Copy link

@nwpray 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

This comment has been minimized.

Copy link

@RedSparr0w 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

This comment has been minimized.

Copy link

@robrecord robrecord commented Oct 9, 2018

RedSparr0w you can shorten this:

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

This comment has been minimized.

Copy link

@sobujbd 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

This comment has been minimized.

Copy link

@axelitus axelitus commented Jun 18, 2019

This all be over once PHP 7.4 arrives:

$name ??= 'joe';
@ben221199

This comment has been minimized.

Copy link

@ben221199 ben221199 commented Sep 1, 2019

Does it throw warnings?

@ben221199

This comment has been minimized.

Copy link

@ben221199 ben221199 commented Sep 1, 2019

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"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment