Can i use ternary operator on left of assignment operator? - php

Like
(true ? $a : $b) = 5;
Or
(true ? &$a : &$b) = 5;
Or
&(true ? $a : $b) = 5;
("It looks like your post is mostly code; please add some more details.")

Make it like this.
$val = 5;
true ? $a = $val : $b = $val;

You can achieve quite the same result using, instead of the variable itself as return value of the ternary expression, the name of the variable.
(true ? $a : $b) won't return the variables, but their content.
This can be achieved like this :
<?php
${true ? "a": "b"} = 5;
echo $a; // outputs 5

No, in PHP, all the 3 codes give syntax error.

Related

How to avoid undefined index warning for chains of 'default' values?

Let's say I want to check for a couple of different parameters, and then fall back to a default value, is there a way to do it without ugly and verbose writing of isset()?
For example in JS we can do:
var someVariable = otherVar || anotherVar || 'fallback here';
The equivalent in PHP would be something like:
$someVariable = (isset($otherVar) ? $otherVar : (isset($anotherVar) ? $anotherVar : 'fallback here'));
which is obviously a mess and horrible to read.
Lots of solutions exist for single fallbacks, i.e.:
$someVariable = $otherVar ?: 'fallback here';
but that doesn't help me with requiring more than one in the line of checks.
Given that I am only interested in whether or not the value is set or truth-y (i.e. I am happy for 1 to be accepted as the used value, and for 0/false/null to be skipped and for the next parameter in the chain to be used), what is the best way to avoid the undefined index warning?
In reality, I would be doing this on arrays in most cases, but not all, and it's probably that they will be different arrays. I may want to use $_POST for the first, then check $_GET under a different key, and then fall back to a default string for example.
Ignoring PHP warnings and notices is not a good idea at all.
But just for the experiment, I can suggest you the error control operator #.
PHP supports one error control operator: the at sign (#). When prepended to an expression in PHP, any error messages that might be generated by that expression will be ignored.
$someVariable = #$otherVar ? #$var : 'fallback here';
echo $someVariable;
// output: fallback here
http://php.net/manual/en/language.operators.errorcontrol.php
You can chain ?: but you'll still need to suppress errors with #.
For example, the following will work similarly to your JavaScript example:
$foo = #$bar ?: #$baz ?: #$qux ?: "I give up";
It's the equivalent of multiple "single fallbacks":
$foo = (#$bar ?: (#$baz ?: (#$qux ?: "I give up")));
Be careful though, ?: only checks for truthyness. There are scenarios where isset() and truthyness do not agree. Additionally, ?: fallback functionality was introduced in PHP 5.3.
If you only care about nullness and have PHP 7 available, it introduced a null coalescing operator.
This is ambiguous and it is deprecated...
$something = $a ? $b : $c ?: $d;
So, you have 2 alternatives for grouping:
$something = $a ? $b : ($c ?: $d); // version 1
$something = ($a ? $b : $c) ?: $d; // version 2
Which one is correct? Let's test this...
$posibilities = [TRUE, FALSE, NULL, [], new stdClass()];
$v1_is_correct = TRUE;
$v2_is_correct = TRUE;
foreach ($posibilities as $a) {
foreach ($posibilities as $b) {
foreach ($posibilities as $c) {
foreach ($posibilities as $d) {
$original = (int)($a ? $b : $c ?: $d);
$v1 = (int)($a ? $b : ($c ?: $d));
$v2 = (int)(($a ? $b : $c) ?: $d);
$v1_is_correct = $v1_is_correct && ($original === $v1);
$v2_is_correct = $v2_is_correct && ($original === $v2);
print "ORIG: $original - V1: $v1 - V2: $v2 \n";
}
}
}
}
print "\n";
$v1_is_correct ? print "V1 is correct \n" : NULL;
$v2_is_correct ? print "V2 is correct \n" : NULL;
Result: V2 is correct.
$a ? $b : $c ?: $d
is equivalent to...
($a ? $b : $c) ?: $d

PHP assign first not-null value

I've got some three values like this:
$a = null
$b = 3;
$c = null
(I never know what will be null: maybe all of them, maybe none of them.)
Following so called lazy loading, I've tried to assign the first not-null value this way:
$d = $a or $b or $c;
(It is similar to JavaScript way var d = a || b; (it will assign b if there is no a).)
But in PHP it seems to not work.
Am I doing it wrong, or what is best and simplest way to do this?
You can use the short ternary operator in PHP 5.3+:
$d = $a ?: $b ?: $c;
Note that this does type coercion like in JS.
Update (PHP 7)
In PHP 7.0+ you would do (called null coalescing - more informations):
$d = $a ?? $b ?? $c;
Try this...
$d = array_filter(array($a, $b, $c))[0]; //newer PHP only
or this:
$d = current(array_filter(array($a, $b, $c))); //warning about references
or this:
$tmp = array_filter(array($a, $b, $c));
$d = current($tmp); //most safe
In PHP 7 you can use the "Null coalescing" operator:
$d = $a ?? $b ?? $c;
This will assign the first non-null value (or null if there isn't one), as the question asked.
Unlike some of the other answers it won't be tripped up by implicit type casting so, for example,
$b = 0; $c = 1;
$d = $a ?? $b ?? $c;
echo $d;
will output 0: It won't mind that $a hasn't been set at all and won't pass over $b even though it type-casts to false.
If you can put variables in an array this can help:
$d = current(array_filter(array($a, $b, $c)));
or this can be a apporach as well:
if(!empty($a)) {
$d = $a;
}
this check may conitnue for all the variables like $b and $c
You can try with:
$d = !is_null($a) ? $a : (!is_null($b) ? $b : $c);
in php you can do it like this:-
`<?php
$a = 1;
$b = null;
$c = null;
$d = $a ? $a:($b?$b:($c?$c:'null'));
echo $d;
?>`

Can the || operator be used to select between values of non-boolean types in PHP?

Is it possible to echo using ||, so that it uses the first variable that evaluates to true?
for example,
$a = false;
$b = 'b';
echo $a || $b || 'neither'; // evaluates to 1 ?
Ternary operator
echo (($a) ? : $b) ? : 'neither';
Ultimate ternary
$a = false;
$b = 'b';
echo ($a)?$a:(($b)?$b:'neither');
echo $a ? $a : ($b ? $b : ($c ? $c : 'neither'));
and You go on like this if have more variables but it will get ugly and hard to read when too long.

Assign variable with the aid of boolean operators

Is there some short way to do this
if (!empty($b))
$a = $b;
else if (!empty($c)) {
$a = $c;
i know you could use ternary operator but its not what i asking like in JavaScript there is way to assign like this
my_var = some_Var || fu_bar || 0;
so if first dont exist it uses second and if second dont exist it uses third one.
is there similar thing in php?
cant think of other way than this:
$a = ! empty($b) ? $b : (! empty($c) ? $c : 0)
you can use one of the two ways whatever suits you. both of these functions will check either we have the non empty variable or not.
1: $a = (isset($b) && $b)?$b:$c;
2: if($b)
$a = $b;
elseif($c)
$a = $c;

How many statements are allowed when using ternary operators (? and :) in PHP?

This code,
count = $a > $b ? $b : $a;
same with:
if($a > $b){
count = $b;
} else {
count = $a;
}
If I want to do this,
if($a > $b){
count = $b;
result = $b." is less than ".$a;
} else {
count = $a;
}
How should I write these using a ternary operator ? :...?
You can actually fit this all into 1 line, but it's difficult to read and probably won't work all of the time.
For the sake of showing you this works:
$a = 7;
$b = 5;
$count = 0;
$result = '';
$count = ($a > $b) ? ((int)$result = $b . ' is less than ' . $a) : $a;
echo $count . '<br />' . $result;
But please never do this in any real code - It will make you very unpopular with anyone who has to work on the same code with you/after you.
If you must use the ternary operator in real code, do it as others have suggested.
count = $a > $b ? $b : $a;
result = count == $b ? $b . " is less than " . $a : "";
You can't do it in a single line. Sorry.
$result = ($a > $b) ? ("$b is less than $a") : ("$a is less than $b");
$count = ($a > $b) ? $b : $a;
Why you're asking how to make your code worse?
What's the point in making the code totally unreadable?
Do not try to put many statements in the ternary operator.
Do not use nested ternary operators.
You have no only write your code as fast as possible, but sometimes you have to read it.
Instead of using this ugly syntax, use common conditional operator.
You really can't, that isn't the point of the ternary operator. You would have to do two statements, or write out the if else.
$count = $a > $b ? $b : $a;
$a > $b ? result = $b." is less than ".$a : ;
Which is I think valid PHP. You may need some parens, and you might need to put a dummy constant after the colon in the second line - just a 0 so PHP has something to do. I'm not sure because I don't PHP.

Categories