Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If null use other variable in one line in PHP

Tags:

php

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 
like image 331
rochal Avatar asked Feb 14 '11 22:02

rochal


People also ask

IS NULL in if condition PHP?

The is_null() function checks whether a variable is NULL or not. This function returns true (1) if the variable is NULL, otherwise it returns false/nothing.

Is null equal to false in PHP?

NULL essentially means a variable has no value assigned to it; false is a valid Boolean value, 0 is a valid integer value, and PHP has some fairly ugly conversions between 0 , "0" , "" , and false .

Is null and empty string the same in PHP?

The value null represents the absence of any object, while the empty string is an object of type String with zero characters. If you try to compare the two, they are not the same.


1 Answers

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

like image 115
Yamiko Avatar answered Oct 03 '22 22:10

Yamiko