php ?: Operator multiple change - php

I want to have what this would output:
if ($user->newsletter == 1) {
echo 'YES'; }
else {
echo 'NO'; }
What I have:
echo $user->newsletter == 0 ?: 'YES' ?: 'NO';
This outputs YES where it should be YES, so this is okay,
but it outputs 1 where it should be NO.
Is there a way how to write this?

Your syntax is a bit odd. This is how you typically use the ternary operator:
echo ($user->newsletter == 1) ? 'YES' : 'NO';
As of PHP 5.3 there is a new way to use the ternary operator:
$foo = $foo ?: $bar;
// which is equivalent to
$foo = $foo ? $foo : $bar;
This short hand is referred to as the Elvis operator.
In your case you can not use this shorthand as you want to transform 0 or 1 into 'Yes' or 'No'.

Related

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 Ternary operator ('shorthand' if-statement)

I've reviewed the PHP Manual here: #3 ternary operators
but I don't understand why all three of these don't function as expected:
$a = array('a','b','c');
//works
if(isset($a)){echo "yes";} else {echo "no";}
//works
isset($a) == true ? $answer = "yes" : $answer = "no";
echo $answer;
//does not work
isset($a) == true ? echo "yes" : echo "no";
Thank you for your consideration.
Since the ternary expression is an expression, its operands have to be expressions as well. echo is not an expression, it's a statement, it can't be used where expressions are required. So the last one doesn't work for the same reason you can't write:
$a = echo "abc";
Rewrite the statement as,
echo isset($a) == true ? "yes" : "no";
The ternary operator doesn't exactly function like an if statement. The ternary operator does not execute the 2nd or 3rd expressions, it returns it.
The correct way is:
echo isset($a) == true ? "yes" : "no";
Also no need to compare it with true:
echo isset($a) ? "yes" : "no";
Because when you use ternary operators you need to count operators precedence and associativity
you can rewrite your code to
echo isset($a) ? "yes" : "no";
Your last line of code should be like;
echo isset($a) == true ? "yes" : "no";

Get value of variable when isset() is used in PHP ternary shorthand operator

In using the shorter ternary operator:
$foo = isset($_GET['bar']) ?: 'hello';
If $_GET['bar'] is set, is it possible for $foo to return the value of $_GET['bar'] instead of true?
Edit: I understand the old school ternary works e.g.,
$foo = isset($_GET['bar']) ? $_GET['bar'] : 'hello';
but I want to use the newschool ternary which is the even shorter version
It sounds like you are asking about the new (as of PHP 7) null coalesce operator. You can do something like:
$foo = $_GET['bar'] ?? 'hello';
echo $foo;
Which if $_GET['bar'] is null will set $foo to hello.
The first operand from left to right that exists and is not NULL. NULL if no values are defined and not NULL. Available as of PHP 7.
Functional demo: https://3v4l.org/0CfbE
$foo = $_GET['bar'] ?? 'hello';
echo $foo . "\n";
$_GET['bar'] = 'good bye';
$foo = $_GET['bar'] ?? 'hello';
echo $foo;
Output:
hello
good bye
Additional reading on it: http://www.lornajane.net/posts/2015/new-in-php-7-null-coalesce-operator
yes you would do it like this
$foo = isset($_GET['bar']) ? $_GET['bar'] : 'hello';
something like this:
$foo = isset($_GET['bar']) ? $_GET['bar'] : 'hello';
I'm not sure I understand your question, but is it something like:
$foo = isset($_GET['bar']) ? true : 'hello';
This will give you one(true) if that variable is set or just hello if it's not.
The answer is no (in PHP5 at least, see chris's answer for PHP7 only). For this reason I tend to use a helper function e.g.
function isset_or(&$variable, $default = NULL)
{
return isset($variable) ? $variable : $default;
}
$foo = isset_or($_GET['bar'], 'hello');

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

Strange ternary operator

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

Categories