If null use other variable in one line in PHP
Asked Answered
L

13

93

Is there in PHP something similar to JavaScript's:

alert(test || 'Hello');

So, when test is undefined or null we'll see Hello, otherwise - we'll see the value of test.

I tried similar syntax in PHP but it doesn't seem to be working right... Also I've got no idea how to google this problem..

thanks

Edit

I should probably add that I wanted to use it inside an array:

$arr = array($one || 'one?', $two || 'two?'); //This is wrong

But indeed, I can use the inline '? :' if statement here as well, thanks.

$arr = array(is_null($one) ? "one?" : $one, is_null($two) ? "two ?" : $two); //OK
Leith answered 14/2, 2011 at 22:45 Comment(2)
If you want to create an array with more than 3 elements like this, have a look at my answer to save yourself a lot ternary operators ;)Etheleneethelin
well, yeah, obviously I'd put it in some sort of utility function ;) thanksLeith
F
63

See @Yamiko's answer below for a PHP7 solution https://mcmap.net/q/224014/-if-null-use-other-variable-in-one-line-in-php

 echo (!$test) ? 'hello' : $test;

Or you can be a little more robust and do this

echo isset($test) ? $test : 'hello'; 
Ferrol answered 14/2, 2011 at 22:47 Comment(4)
Why check against !$test and not just do $test ? $test : 'hello'; instead?Starstudded
Well he stated if $test was undefined or null he wanted to see 'Hello', if the value of $test was int(0) he'd still see hello even though it's set and not null because php interprets 0 as false unless you're using ===. So just to be safe he should check to see if $test is set and not null. At least that was my logic.Ferrol
I understand but your resolution is very confusing :( . It should not be a accepted answer according to "If null use other variable in one line in PHP". The answer of @yamiko is very simple as well as useful.lBackbreaking
The || is_null() is redundant here, isset($var) returns false if $var is nullMononuclear
E
83

From PHP 7 onwards you can use something called a coalesce operator which does exactly what you want without the E_NOTICE that ?: triggers.

To use it you use ?? which will check if the value on the left is set and not null.

$arr = array($one ?? 'one?', $two ?? 'two?'); 
Epicycle answered 23/3, 2015 at 18:21 Comment(0)
E
81

you can do echo $test ?: 'hello';

This will echo $test if it is true and 'hello' otherwise.

Note it will throw a notice or strict error if $test is not set but...

This shouldn't be a problem since most servers are set to ignore these errors. Most frameworks have code that triggers these errors.


Edit: This is a classic Ternary Operator, but with the middle part left out. Available since PHP 5.3.

echo $test ? $test : 'hello'; // this is the same
echo $test ?: 'hello';        // as this one

This only checks for the truthiness of the first variable and not if it is undefined, in which case it triggers the E_NOTICE error. For the latter, check the PHP7 answer below (soon hopefully above).

Epicycle answered 21/12, 2012 at 0:31 Comment(7)
I agree but major libraries and plugins for them trigger them all the time so they are usually ignored in production. Also this type of error is E_NOTICE which is something that is safe to ignore. I personally don't like triggering any kind of error including E_NOTICE but this type of error is more about best practices than an actual error that needs to be fixedEpicycle
Also I know premature optimization is bad and all but triggering a notice causes the error handling function (whether PHP's default or a custom one) to be called even if that function ends up ignoring the error due to your error_reporting setting, and that can be slow especially if you do it within a loop.Fireside
What's the name of this ?: operator? Can someone link to the docs?Mckale
@Mckale It is classic ternary operator, but with the middle part left out. So it kind of makes it a shorthand ternary operator. Available since PHP 5.3.Libyan
@dboris Thank you!Mckale
Aka the elvis operator :DBlunge
Neat, I never knew about this. You could say ?: is to ? as += is to =... kinda.Germain
F
63

See @Yamiko's answer below for a PHP7 solution https://mcmap.net/q/224014/-if-null-use-other-variable-in-one-line-in-php

 echo (!$test) ? 'hello' : $test;

Or you can be a little more robust and do this

echo isset($test) ? $test : 'hello'; 
Ferrol answered 14/2, 2011 at 22:47 Comment(4)
Why check against !$test and not just do $test ? $test : 'hello'; instead?Starstudded
Well he stated if $test was undefined or null he wanted to see 'Hello', if the value of $test was int(0) he'd still see hello even though it's set and not null because php interprets 0 as false unless you're using ===. So just to be safe he should check to see if $test is set and not null. At least that was my logic.Ferrol
I understand but your resolution is very confusing :( . It should not be a accepted answer according to "If null use other variable in one line in PHP". The answer of @yamiko is very simple as well as useful.lBackbreaking
The || is_null() is redundant here, isset($var) returns false if $var is nullMononuclear
K
11

As per the latest version use this for the shorthand

$var = $value ?? "secondvalue";
Kev answered 16/7, 2020 at 6:4 Comment(2)
Yes! Thank you for this answer. Seems that the null-coalescing operator was added in PHP 7. php.net/manual/en/…Susannsusanna
For PHP >7 this is definitely the cleanest way to do it!Westcott
N
6

One-liner. Super readable, works for regular variables, arrays and objects.

// standard variable string
$result = @$var_str ?: "default";

// missing array element
$result = @$var_arr["missing"] ?: "default";

// missing object member
$result = @$var_obj->missing ?: "default";

See it in action: Php Sandbox Demo

Nicole answered 22/2, 2018 at 0:47 Comment(0)
M
5

I'm very surprised this isn't suggested in the other answers:

echo isset($test) ? $test : 'hello';

From the docs isset($var) will return false if $var doesn't exist or is set to null.

The null coalesce operator from PHP 7 onwards, described by @Yamiko, is a syntax shortcut for the above.

In this case:

echo $test ?? 'hello'; 
Mononuclear answered 23/2, 2018 at 15:35 Comment(0)
E
1

If you want to create an array this way, array_map provides a more concise way to do this (depending on the number of elements in the array):

function defined_map($value, $default) {
    return (!isset($value) || is_null($value)) ? $default : $value;
    // or return $value ? $default : $value;
}

$values = array($one, $two);
$defaults = array('one', 'two');

$values = array_map('defined_map', $values, $defaults);

Just make sure you know which elements evaluate to false so you can apply the right test.

Etheleneethelin answered 14/2, 2011 at 22:58 Comment(0)
Q
1

Since php7.4, you can use the null coalescing assignment, so that you can do

$arr = array($one ??= "one?", $two ??= "two ?");

See the docs here

Qoph answered 23/2, 2022 at 23:57 Comment(0)
R
0

There may be a better way, but this is the first thing that came to my mind:

 echo (!$test) ? "Hello" : $test;
Remission answered 14/2, 2011 at 22:47 Comment(0)
S
0

Null is false in PHP, therefore you can use ternary:

alert($test ? $test : 'Hello');

Edit:

This also holds for an empty string, since ternary uses the '===' equality rather than '=='

And empty or null string is false whether using the '===' or '==' operator. I really should test my answers first.

Starstudded answered 14/2, 2011 at 22:48 Comment(0)
L
0

Well, expanding that notation you supplied means you come up with:

if (test) {
    alert(test);
} else {
    alert('Hello');
}

So it's just a simple if...else construct. In PHP, you can shorten simple if...else constructs as something called a 'ternary expression':

alert($test ? $test : 'Hello');

Obviously there is no equivalent to the JS alert function in PHP, but the construct is the same.

Lucilius answered 14/2, 2011 at 22:50 Comment(0)
T
-1
alert((test == null || test == undefined)?'hello':test);
Tao answered 14/2, 2011 at 22:47 Comment(0)
A
-1

I recently had the very same problem.This is how i solved it:

<?php if (empty($row['test'])) {
                    echo "Not Provided";} 
                        else {
                    echo $row['test'];}?></h5></span></span>
              </div>

Your value in the database is in variable $test..so if $test row is empty then echo Not Provided

Anatol answered 14/1, 2017 at 17:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.