Skip to content

Instantly share code, notes, and snippets.

@JeffreyWay
Created July 28, 2012 19:09
Show Gist options
  • Star 57 You must be signed in to star a gist
  • Fork 20 You must be signed in to fork a gist
  • 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?

@isimmons
Copy link

@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
Copy link

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

@everzet
Copy link

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
Copy link

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
Copy link

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
Copy link

zecho commented Jul 30, 2012

try with:

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

also:

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

@everzet
Copy link

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
Copy link

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
Copy link

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
Copy link

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
Copy link

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
Copy link

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
Copy link

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