I have the following code:
if(count($a) > 0){
$a = $b;
} else {
$c = $b;
}
Is it possible to re-write this, using ternary operators? or any way to shorten it? Thanks!
(count($a) > 0) ? $a = $b : $c = $b;
Yes, you can use ternary operators
cond ? true : false
You can see the full documentation here
http://www.php.net/manual/language.operators.comparison.php#language.operators.comparison.ternary
try-
<?php
$a=array(1,23,3,4,5);
echo (count($a) > 0) ? "true": "false";
?>
OUTPUT-true
count ($a) > 0 AND $a = $b OR $c = $b;
Related
From what I see operator precedence makes sense in these two examples:
$a = false;
$b = true;
$c = $a || $b;
Here $c is true
$a = false;
$b = true;
$c = $a or $b;
Here $c is false
I understand the reasoning behind it. However the following:
$a = false;
$b = true;
return $a or $b;
Returns true, which puzzles me.
What is the reason for this?
or has lower precedence than =, so this:
$c = $a or $b;
Becomes this:
($c = $a) or $b;
But this doesn't make sense:
(return $a) or $b;
So you get this:
return ($a or $b);
Within an expression, operator precedence applies. =, || and or are all operators and $c = $a or $b is an expression. And according to operator precedence it evaluates as ($c = $a) or $b.
However, return is a statement. return is not an operator and does not group by operator precedence. It always evaluates as return <expression>, and therefore always as return ($a or $b).
The result of the expression $c = $a or $b is true BTW. $c is being assigned false in the course of the expression, but the expression overall returns the value true ($b). So even this would return true:
return $c = $a or $b;
where:
$b = true;
$c = 0;
$a = ($a ? ($a ? $b : $c) : ($c ? $a : $b));
I'm not sure how to work out a.
So I understand that this is a shorthand operator, and usually it's a case of:
$value ? true : false
meaning
if $a = true { true } else { false };
so:
if $a{
if $a{
true;}
else{
0;};
else{
if $0{
$a;}
else{
true;}
};
does this make the value of $a true?
The value of $a would be true
$b = true;
$c = 0;
$a = ($a ? ($a ? $b : $c) : ($c ? $a : $b));
The shorthand can be interpreted like this:
if($a) {
if($a) {
$a = $b;
} else {
$a = $c;
}
} else {
if($c) {
$a = $a;
} else {
$a = $b;
}
}
Because $a is false for not existing in the first place, it immediately jumps to the else statement in that. So the only part that matters to you is:
if($c) {
$a = $a;
} else {
$a = $b;
}
0 is the same as false, so $c will come back as false, therefore $a is equal to $b, which is true.
Edit:
There is some discussion on the notice that is thrown, but this fails to account for the fact that notices are not truly errors and because of this there is no interruption to the code. The result is not Notice: Undefined variable: a, the "result" (think these people mean output) would be blank if it weren't for us determining the value of $a at the end with var_dump. The question was as to what the value of $a becomes, not what appears on your screen.
Something displaying on your screen in re to a variable not being set has nothing to do with the value of what $a is.
If you execute the following code, the notice is not the only thing realized:
$b = true;
$c = 0;
$a = ($a ? ($a ? $b : $c) : ($c ? $a : $b));
var_dump($a);
So the output is:
E_NOTICE : type 8 -- Undefined variable: a -- at line 5
bool(true)
The fact that a notice was thrown does not prevent $a from becoming true.
Also notices are easily suppressed...
error_reporting(0);
$b = true;
$c = 0;
$a = ($a ? ($a ? $b : $c) : ($c ? $a : $b));
var_dump($a);
would result in $a still becoming true, and without seeing the notice.
bool(true)
If you run the code as is, you would get: Notice: Undefined variable: a in myfile.php on line 4
Therefore, I would postulate $a is set somewhere earlier. Yet, whatever value $a has prior, if $a is can be evaluated to true or false, $a would still be true after running your code for the following reason:
If $a were true, then the first part would yield $a = $b and we know $b = true.
if(TRUE) {
if(TRUE) {
$a = $b; //AND $b == TRUE
} else {
$a = $c;
}
} else {
...
}
If $a were false, then the second part would yield $a = $b again
if(FALSE) {
...
} else {
if(0) { // 0 will equate to FALSE
...
} else {
// 0 is the same as FALSE so we end up again with $a = $b
$a = $b; //AND $b == TRUE
}
}
In fact, if you run this code, it will show you the value of $a is true both times:
<?php
$a = false;
$b = true;
$c = 0;
$a = ($a ? ($a ? $b : $c) : ($c ? $a : $b));
echo $a;
$a = true;
$b = true;
$c = 0;
$a = ($a ? ($a ? $b : $c) : ($c ? $a : $b));
echo $a;
I want to convert this code to a ternary operator:
if (isset($a)) {
$arr[$k] += $c;
}
else {
$arr[$k] = $c;
}
I can do it if it were a single operator, but, operators are different in if and else.
How to do it?
Isn't it just:
$arr[$k] = isset(a$) ? ($arr[$k]+$c) : $c
or equivalently:
$arr[$k] = $c + (isset($a) ? $arr[$k] : 0)
Possible conversion algorithm with your case (like school algebra)
Direct conversion.
isset($a) ? ($arr[$k] += $c) : ($arr[$k] = $c);
Explode +=
isset($a) ? ($arr[$k] = $arr[$k] + $c) : ($arr[$k] = $c);
Move assignment to the left
$arr[$k] = isset($a) ? ($arr[$k] + $c) : ($c);
Move $c
$arr[$k] = (isset($a) ? $arr[$k] : 0) + $c;
And variant without ternary(as bonus).
$arr[$k] = $c + isset($a) * $arr[$k];
I really enjoy || operator in JavaScript, where we can do inline conditional assignation.
var a = 0;
var b = 42;
var test = a || b || 'default value';
console.log(test); // 42
This is clear to read, and don't take too many lines.
In PHP, this logical operator return booleans:
$a = 0;
$b = 42;
$test = $a || $b || 'default value';
print_r($test); // bool(true)
Of course, we can do inline assignation using ternaries:
$test = $a ? $a : $b ? $b : 'default';
print_r($test); // int(42)
But this make code ambiguous, this is not that easy to read.
So here my question come:
Do you know a nice PHP hack to do inline conditional assignation ?
In PHP 5.3+ you can do this:
$test = $a ?: ($b ?: 'default value');
This will work as long as you don't need to short-circuit side effects:
function either_or() {
$nargs = func_num_args();
if ($nargs == 0) {
return false;
}
$args = func_get_args();
for ($i = 0; $i < $nargs-1; $i++) {
if ($args[$i]) {
return $args[$i];
}
}
return $args[$nargs-1];
}
$test = either_or($a, $b, "Default value");
Say I have a string, $char. $char == "*".
I also have two variables, $a and $b, which equal "4" and "5" respectively.
How do I get the result of $a $char $b, ie 4 * 5 ?
Thanks :)
You can use eval() as suggested by #konforce, however the safest route would be something like:
$left = (int)$a;
$right = (int)$b;
$result = 0;
switch($char){
case "*":
$result = $left * $right;
break;
case "+";
$result = $left + $right;
break;
// etc
}
safest method is a switch construct:
function my_operator($a, $b, $char) {
switch($char) {
case '=': return $a = $b;
case '*': return $a * $b;
case '+': return $a + $b;
etc...
}
}
The easiest but most dangerous method is to use eval.
$c = eval("return $a $char $b;");
take a look at the eval() function. you will need to build a proper php command and run inside the eval() to extract out the result.
You can do with eval however I would not suggest using eval.
If there is case operator can by anything you should check what operator is before using
switch($char)
{
case '*':
$result= $a * $b;
break;
case '+':
$result= $a + $b;
break;
}
<?php
$a = 'alex';
$b = "alex";
$c = "==";
function abc($a,$b,$c){
$d = 'return ($a '.$c.' $b) ? true : false;';
return eval($d);
}
if(abc($a,$b,$c)){
echo "condition true";
}else{
echo "condition false";
}
// echo $e;
?>