Assign variable with the aid of boolean operators - php

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;

Related

Can i use ternary operator on left of assignment operator?

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.

Simplify an If/Else statement with null checks

I'd like a way to simplify an if/else statement that concatenates two values together, but also checks for null values before using the variables.
For example:
if (isset($A,$B)) {
$C = $A . $B;
}
elseif(isset($A)) {
$C = $A;
}
elseif(isset($B)) {
$C = $B;
}
Before concatenating $A with $B I need to make sure neither are NULL. If they both contain a value, then I want to assign the concatenation to the variable $C. If either value is null, then I want just one value assigned to $C.
The above works fine when I only have two variables, but what if a third variable $D were added and I needed to concatenate into $C and still check for nulls. Then I would need to check first for ABD, then AB, then BD, then A, then B, then D. It will get really unruly.
So how can I simplify the code and allow for more variables to be added in the future if necessary?
How about the following:
<?php
$a=NULL;
$b="hello ";
$c=NULL;
$d="world\n";
$all = implode(array($a,$b,$c,$d));
echo $all;
?>
This prints
hello world
without any errors. It is an implementation of the comment that #wor10ck made - but he didn't seem to follow up with a full answer / example and I thought his suggestion was worth fleshing out.
EDIT for people who don't read comments - #Keven ended up using
$result = implode(array_filter($array));
which is a nice robust way to remove the NULL elements in the array.
$C = (isset($A) ? $A : '') . (isset($B) ? $B : '') . (isset($D) ? $D : '');
You might find this usefull
$C = "";
$C .= (isset($A) ? $A : "").(isset($B) ? $B : "");
The question mark operator returns the left part before the : symbol if the statement is true, and right if false. Hoever i think that nesting statements in if block is more optimised.
<?php
// I assume $res is the variable containing the result of the concatenations
$res = '';
if(isset($a))
$res .= $a;
if(isset($b))
$res .= $b;
if(isset($c))
$res .= $c;
// ...
$A = 'a';
$B = 'b';
$C = '';
$C .= isset($A) ? $A : '';
$C .= isset($B) ? $B : '';
$C .= isset($D) ? $D : '';
echo $C;

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;
?>`

Fallthrough variable assignment in PHP? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Coalesce function for PHP?
I'm not sure what this is normally called, but I hope the title communicates well enough. What I have is a handful of variables some of which might be null.
I want to do:
$a = $b || $c || $d;
Where $a ends up being = to the first non-null variable.
To my knowledge, PHP doesn't support this in the same way JavaScript does.
You can, however do something like this:
$a = $b ? $b : ($c ? $c : $d);
A more general solution:
function fallthrough($arr) {
//$arr should be an array of possible values. The first non-null value is returned
do $a = array_shift($arr);
while($a === null && $arr);
return $a;
}
<?php
$a = 0;
$b = false;
$c = true; //should become this
$d = '1';
$e = $a ?: $b ?: $c ?: $d;
var_dump($e);
//bool(true)
//should be '1' if order is different
$e = $a ?: $b ?: $d ?: $c;
var_dump($e);
//string(1) "1"
... however ?: is kinda new, you will confuse your colleagues / fellow coders.
I don't think that's possible. I think you'd have to use some other, more laborious, way. I.e. make an array of the variables, iterate through it until you find a non-null value and break the loop, like so:
$vars = array("b" => $b, "c" => $c, "d" => $d);
foreach($vars as $var) {
if($var != null) {
$a = $var;
break;
}
}
Well, like some other answers here say, you can use the shorthand way of writing this, but writing readable code is important too. The above code is pretty readable.

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