Strange ternary operator - 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.

Related

Message: Trying to get property of non-object error in php [duplicate]

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

Why does the ternary operator work with print but not with echo in php?

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 if shorthand and echo in one line - possible?

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

Assign variable within condition if true

I know you can assign a variable in a condition like this:
if ($var = $foo)
However I don't need to do anything in the condition itself, so I'm often left with empty brackets. Can I simply assign $var if $foo is true in some other way without needing to do something else later?
Also can I assign $var to $foo if $foo is true but if $foo is false do something else? Like:
if ($var = !$foo) {
if ($var = !$bar) {
//Etc...
}
}
Basically I want to have more fallbacks/defaults.
#chandresh_cool's suggestion is right but to allow multiple possiblities / fallbacks you would have to nest the ternary expressions:
$var = ($foo == true) ? $foo:
($bar == true) ? $bar:
($fuzz == true) ? $fuzz:
$default;
Note: the first 3 lines end in colons not semi-colons.
However a simpler solution is to do the following:
$var = ($foo||$bar||$fuzz...);
Although this is a very old post. Fallback logic on falsify values can be coded like this.
$var = $foo ?: $bar ?: "default";
In this case when $foo is a falsified value (like false, empty string, etc.) it will fall back to $bar otherwise it uses $foo.
If bar is a falsified value, it will fallback to the string default.
Keep in mind, that this works with falsified values, and not only true.
example:
$foo = "";
$bar = null;
$var = $foo ?: $bar ?: "default";
$var will contain the text default because empty strings and null are considered "false" values.
[update]
In php 7 you can use the new null coalescing operator: ??, which also checks if the variable exists with isset(). This is usefull for when you are using a key in an array.
Example:
$array = [];
$bar = null;
$var = $array['foo'] ?? $bar ?? "default";
Before php 7 this would have given an Undefined index: foo notice. But with the null coalescing operator, that notice won't come up.
Instead you can Use ternary operator like this
$var = ($foo == true)?$foo:"put here what you want";
You can assign values like this:
$var = $foo;
Setting them within an if statement is also possible, PHP will evaluate the resulting $var which you just assigned.
I dont really get your question, but you could do something like this:
if(!($var = $foo)){
//something else.
}

In PHP can you use || (or) in the same way as javascript?

Can I use the OR argument in this way in PHP? Meaning if $x is null assign $y to $var.
$var = $x || $y
Simple question, cheers!
No. PHP's boolean operators evaluate to true or false, not the value of the operands as in Javascript. So you'll have to write something like this:
$var = $x ? $x : $y;
Since 5.3, you can write this though, which basically has the same effect as Javascript's ||:
$var = $x ?: $y;
That requires that $x exists though, otherwise you should check with isset first.
No, in this way you assign a boolean to $var
$var = $x or $y;
means: $var is true, if $x or $y. You are looking for the ternary operator
$var = isset($x) ? $x : $y;
// or
$var = empty($x) ? $y : $x;
The ternary operator always works like
$var = $expressionToTest
? $valueIfExpressionTrue
: $valueIfExpressionFalse
With PHP5.3 or later you can omit $valueIfExpressionTrue
$var = $expressionToTest ?: $valueIfExpressionFalse;
$x=0;
$y=9;
$var = ($x)?$x:$y;
echo $var;
if variable x is null then var will be 9,or else it will be value of x.
This question is already answered, but I juist wanted to point your attention to the other usage of OR and AND operators in PHP
defined('SOMETHING') OR define('SOMETHING', 1);
if this case if SOMETHING is not defined (defined('SOMETHONG') evaluates to false) expression after OR will be evaluated
$admin AND show_admin_controls();
if $admin is evaluated to boolean true, show_admin_controls() function will be called
I usually use it to check if some constant is defined, but I've seen a lot of examples of good-looking and really well-readable code using this constructions for other purposes.

Categories