What's the best, preferred way of writing if shorthand one-liner such as:
expression ? $foo : $bar
Plot twist: I need to echo $foo or echo $bar. Any crazy tricks? :)
<?=(expression) ? $foo : $bar?>
edit: here's a good read for you on the topic
edit: more to read
echo (expression) ? $foo : $bar;
The ternary operator evaluates to the value of the second expression if the first one evaluates to TRUE, and evaluates to the third expression if the first evaluates to FALSE. To echo one value or the other, just pass the ternary expression to the echo statement.
echo expression ? $foo : $bar;
Read more about the ternary operator in the PHP manual for more details: http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary
Great answers above, and I love when programmers ask questions like this to create clear, concise and clinical coding practices. For anyone that might find this useful:
<?php
// grabbing the value from a function, this is just an example
$value = function_to_return_value(); // returns value || FALSE
// the following structures an output if $value is not FALSE
echo ( !$value ? '' : '<div>'. $value .'</div>' );
// the following will echo $value if exists, and nothing if not
echo $value ?: '';
// OR (same thing as)
echo ( $value ?: '' );
// or null coalesce operator
echo $value ?? '';
// OR (same thing as)
echo ( $value ?? '' );
?>
References:
PHP Operators Comparison
Null Coalesce Operator
Related
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
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).
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?');
See #Yamiko's answer below for a PHP7 solution https://stackoverflow.com/a/29217577/140413
echo (!$test) ? 'hello' : $test;
Or you can be a little more robust and do this
echo isset($test) ? $test : 'hello';
As per the latest version use this for the shorthand
$var = $value ?? "secondvalue";
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
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';
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.
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
There may be a better way, but this is the first thing that came to my mind:
echo (!$test) ? "Hello" : $test;
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.
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.
alert((test == null || test == undefined)?'hello':test);
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
This question already has answers here:
Stacking Multiple Ternary Operators in PHP
(11 answers)
Closed 4 years ago.
I have a method that I'm checking if param is null, but if I use a ternary operator to make sure the false result isn't a string, I don't get the same expected result... I am a full stack .NET dev by day, but do some PHP free lance and this just stumped me...
$param = null;
// $active evaluates to true
$active = is_null($param) ? true : false;
// $active evaluates to false
$active = is_null($param) ? true : is_string($param)
? (strtolower($param) === 'true')
: true;
I have used nested ternary operators in C# and JavaScript what feels like countless times, but I don't know if I have ever tried in PHP... does PHP attempt to evaluate all nested ternary operations prior to expressing a result or is there something I'm missing here since from my understanding in this case, the ternary operator should be short circuited and evaluated to true in both circumstances.
The ternary operator is left associative unlike most other languages such as C#. The code:
$active = is_null($param)
? true
: is_string($param)
? (strtolower($param) === 'true')
: true;
is evaluated as follows:
$active = ((is_null($param) ? true : is_string($param))
? (strtolower($param) === 'true') : true);
You must explicitly add parenthesis to make sure ?: works the way it does in familiar languages:
$active = is_null($param)
? true
: (is_string($param)
? (strtolower($param) === 'true')
: true);
You need to wrap your second ternary condition with parenthesis (),
<?php
$param = null;
// $active evaluates to true
$active = is_null($param) ? true : false;
echo "Simple ternary result = $active".PHP_EOL;
// $active evaluates to true
$active = is_null($param) ? true : (is_string($param)? (strtolower($param) === 'true'): true);
echo "Nested ternary result = $active";
?>
Note:
It is recommended that you avoid "stacking" ternary expressions. PHP's
behaviour when using more than one ternary operator within a single
statement is non-obvious:
See Example #4 here at http://php.net/manual/en/language.operators.comparison.php
Example #4 Non-obvious Ternary Behaviour
<?php
// on first glance, the following appears to output 'true'
echo (true?'true':false?'t':'f');
// however, the actual output of the above is 't'
// this is because ternary expressions are evaluated from left to right
// the following is a more obvious version of the same code as above
echo ((true ? 'true' : false) ? 't' : 'f');
// here, you can see that the first expression is evaluated to 'true', which
// in turn evaluates to (bool)true, thus returning the true branch of the
// second ternary expression.
?>
DEMO: https://3v4l.org/gW8pk
This is a well-known problem with PHP. I doubt it will ever be fixed. Use parentheses, or if..else or switch statements, to get the behaviour you want.
(In technical terms, the ternary operator in PHP is "left associative", while that in every other language with this operator is "right associative". The latter is the more logical behaviour for this operator.)
This works:
$number = 1;
$number == 1? print 'yes' : print 'no';
but this doesn't work:
$number = 1;
$number == 1? echo 'yes' : echo 'no';
Why is this happening in PHP?
The parameters to the ternary operator have to be expressions. print 'yes' is an expression, but echo 'yes' is not, because echo is special syntax.
Use the ternary operator as the argument of echo, not the other way around.
echo $number == 1 ? 'yes' : 'no';
It's the same reason you can't write:
$var = echo 'yes';
Check your log for a warning. The ternary operator must return a value. print returns 1 always, but echo does not return a value.
Regarding your comment about putting echo in a function, functions that don't explicitly return a value return null by default, therefore, the function is indeed returning a value:
http://php.net/manual/en/functions.returning-values.php
http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary
http://php.net/manual/en/function.print.php
http://php.net/manual/en/function.echo.php
<?php echo (isset($var)) ?: $var; ?>
Is this syntax correct? What will this display if $var won't be set, empty string or null? Is it ok to use this?
This:
<?php echo (isset($var)) ?: $var; ?>
do the same as this:
<?php
if (isset($var)) {
// do nothing
} else {
echo $var;
}
?>
So you are trying to display variable if its empty/null/etc...
If function:
<?php $k= (cond ? do_if_true : do_if_false); ?>
$k could be new variable, echo, etc.
cond - isset, $z==$y, etc.
The syntax is correct, the usage is not. Say here:
$var = something();
echo $var ?: 'false';
This is equivalent to:
$var = something();
if ($var) {
echo $var;
} else {
echo 'false';
}
or shorthand for $var ? $var : 'false'.
Your example is pointless since it outputs the result of isset($var) (true) if $var is set and $var otherwise.
You need echo isset($var) ? $var : null or if (isset($var)) echo $var, and there's no shortcut for it.
The syntax is fine.
If $var is set then it will output, if it is not, it will throw an Notice about the echo of $var which is unset.
if your error_reporting is set to E_NONE then you will just see a white screen, if the $var is set then you will see the value of $var
This will echo $var either way.
Since PHP 5.3, it is possible to leave out the middle part of the
ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1
evaluates to TRUE, and expr3 otherwise.
So if $var is set, it echos $var (since that evaluates to TRUE), if its not set to anything or evaluates to false, your manually asking it to echo $var anyway.
ideally you want:
(condition ? if_true_then_do_this : if_false_then_do_this)
in shorthand this becomes
(condition ? ? false)
and since you have specified $var in both places, you will get $var, either way. You want this:
echo ($var?:"null");
Nope, this syntax is incorrect.
By the time of echoing, all variables have to be set and properly formatted.
Otherwise means a developer have no idea where their variables come from and what do they contain - a straight road to injection.
So, the proper syntax would be
<?=$var?>
As for the ternaries - I don't like them.
The code no have sense, generates a notice or echo 1, you can't print a $var which isn't set
<?php (isset($var)) ? echo "" : echo $var; ?>
you can use this one.
In PHP I find myself writing code like this frequently:
$a = isset($the->very->long->variable[$index])
? $the->very->long->variable[$index]
: null;
Is there a simpler way to do this? Preferably one that doesn't require me to write $the->very->long->variable[$index] twice.
An update, because PHP 7 is now out and is a game-changer on this point ; the previous answers are about PHP 5.
PHP 7 solves this issue. Because you are true at saying that it is frequent to write this in PHP, and that's absolutely not elegant.
In PHP 7 comes the Null Coalesce Operator (RFC), which is a perfect shorthand for the isset ternary condition.
Its goal is to replace this type of condition:
$var = isset($dict['optional']) ? $dict['optional'] : 'fallback';
By that:
$var = $dict['optional'] ?? 'fallback';
Even better, the null coalesce operators are chainable:
$x = null;
# $y = null; (undefined)
$z = 'fallback';
# PHP 7
echo $x ?? $y ?? $z #=> "fallback"
# PHP 5
echo isset($x) ? $x : (isset($y) ? $y : $z)
The null coalesce operator acts exactly like isset() : the subject variable's value is taken if:
The variable is defined (it exists)
The variable is not null
Just a note for PHP beginners: if you use the ternary condition but you know that the subject variable is necessarily defined (but you want a fallback for falsy values), there's the Elvis operator:
$var = $dict['optional'] ?: 'fallback';
With the Elvis operator, if $dict['optional'] is an invalid offset or $dict is undefined, you'll get a E_NOTICE warning (PHP 5 & 7). That's why, in PHP 5, people are using the hideous isset a ? a : b form when they're not sure about the input.
Sadly no, because the RFC has been declined. And because isset is not a function but a language construct you cannot write your own function for this case.
Note: Because this is a language construct and not a function, it cannot be called using variable functions.
If you only assign null instead of the non set variable, you can use:
$a = #$the->very->long->variable[$index];
# makes that instruction throw no errors
Assuming you know that $the->very->long->variable is set, and you're just worried about the array index....
$x = $the->very->long->variable;
$a = isset($x[$index]) ? $x[$index] : null;
Or for a more generic variant that you can use around you code:
function array_valifset($arr,$k, $default=null) {
return isset($arr[$k]) ? $arr[$k] : $default;
}
then call it like this for any array value:
$a = array_valifset($the->very->long->variable,$index);
I stumbled across the same problem and discovered that referencing an array element does not issue a notice or warning but returns null (at least PHP 5.6).
$foo = ['bar' => 1];
var_dump($bar = &$foo['bar']); // int 1
var_dump($baz = &$foo['baz']); // null
Inside an if statement:
if($bar = &$foo['bar']) {
echo $bar;
}
if($baz = &$foo['baz']) {
echo $baz;
}