This question already has answers here:
Stacking Multiple Ternary Operators in PHP
(11 answers)
Closed 5 years ago.
function get_status($data) {
return ($data->cm_status == 'Y') ? 'Active' :
($data->cm_status == 'N') ? 'Inactive' : '-';
}
I should get Active if $data->cm_status is Y
I should get Inactive if $data->cm_status is N
I should get - if $data->cm_status is anything else
But actually in all case I am getting Inactive
What is the mistake I am doing?
references to your answers appreciated
You need to wrap the inner ternary operator in brackets for the results to be produced correctly, like this
function get_status($data) {
return $data->cm_status == 'Y' ? 'Active' :
($data->cm_status == 'N' ? 'Inactive' : '-');
}
A more readable approach could be to use a switch instead, using nested ternary operators could easily confuse and cause more chaos than it solves. A switch would look like this
function get_status($data) {
switch ($data->cm_status) {
case "Y":
return 'Active';
case "N":
return 'Inactive';
default:
return '-';
}
}
This also assumes that the input would always be upper-case, you could add additional code to compare regardless if its upper or lowercase.
In case of nested ternary operator the composite one should be inside a couple of brackets. So try this;
function get_status($data) {
return ($data->cm_status == 'Y') ? 'Active' :(($data->cm_status == 'N') ? 'Inactive' : '-')
}
Notice the "()" in second ternary conditional operator.
Use this:
function get_status($data) {
return ($data->cm_status == 'Y') ? 'Active' :
(($data->cm_status == 'N') ? 'Inactive' : '-');
}
Related
This question already has answers here:
Stacking Multiple Ternary Operators in PHP
(11 answers)
Closed 2 years ago.
I was making a clamp() function in php, and decided to go for a nested ternary expression just to try it.
In the end, I settled with this (working) function :
function clamp($value, $min, $max){
return
$value<$min ? $min
: ($value>$max ? $max
: $value);
}
However, why are the brackets around the second expression required? I had tried removing them afterward :..
function clamp($value, $min, $max){
return
$value<$min ? $min
: $value>$max ? $max
: $value;
}
... but in this version, it will return $max if $value is smaller than $min. I just don't understand how it comes to that result.
I had hear of php having "left associativity" with ternary, though I never understood what it meant:
Take
$bool ? "a" : $bool ? "b" : "c"
Right associativity is: $bool ? "a" : ($bool ? "b" : "c")
Left associativity is : ($bool ? "a" : $bool) ? "b" : "c"
So in the end php will always it evaluate to either b or c.
Bonus:
$bool ? $bool ? "c" : "b" : "a"
Here is a syntax that I think wouldn't change meaning based on associativity.
I wonder whether people managed to find a pretty indentation for this variant.
This question already has answers here:
Reference Guide: What does this symbol mean in PHP? (PHP Syntax)
(24 answers)
Closed 7 years ago.
what does $mark_state_id = $r['mark_state_id'] == 2 ? 1 : 2; mean ?
Friends, what is it doing above?
It is better written as (with brackets for clarity):
$mark_state_id = ($r['mark_state_id'] == 2 ? 1 : 2);
which means "If $r['mark_state_id'] is equal to 2, then return 1, else return 2. Then $mark_state_id will take the returned value above. This is equivalent to:
$mark_state_id;
if($r['mark_state_id'] == 2){
$mark_state_id = 1;
} else {
$mark_state_id = 2;
}
It uses the ternary operator as a shorthand for if/else.
That is a ternary operator, what is says is: if $r['mark_state_id'] = 2 then $mark_state_id = 1 else $mark_state_id = 2.
Which basically means this if/else statement:
if($r['mark_state_id'] == 2){
$mark_state_id = 1;
} else {
$mark_state_id = 2;
}
The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates to TRUE, and expr3 if expr1 evaluates to FALSE.
It will check $r['mark_state_id'] == 2. If it is true then it will assign 1 else 2.
$mark_state_id = $r['mark_state_id'] == 2 ? 1 : 2; similar to -
if($r['mark_state_id'] == 2) {
$mark_state_id = 1;
} else {
$mark_state_id = 2;
}
Ternary Operator
The ternary operator is an expression, and that it doesn't evaluate to a variable, but to the result of an expression. This is important to know if you want to return a variable by reference. The statement return $var == 42 ? $a : $b; in a return-by-reference function will therefore not work and a warning is issued in later PHP versions.
This question already has answers here:
What does the question mark and the colon (?: ternary operator) mean in objective-c?
(13 answers)
Closed 8 years ago.
I am new to php developing but so far have been able to do whatever I want. I recently came across a strange syntax of writing a return statement:
public static function return_taxonomy_field_value( $value )
{
return (! empty(self::$settings['tax_value']) ) ? self::$settings['tax_value'] : $value;
}
I get the return() and the !empty() but after that it has a ? and that's where I get lost. Any help is much appreciated! Thanks guys
This is a ternary operator, a short version of the if statement.
This:
$a = $test ? $b : $c;
is the same as:
if($test)
{
$a=$b;
}
else
{
$a=$c;
}
so basically your example is equivalent to:
if(! empty(self::$settings['tax_value'])
{
return self::$settings['tax_value'];
}
else
{
return $value;
}
You can find some more info here, together with some tips for precautions when using ternary operators.
Important note about the difference from other languages
Since the question is marked as a duplicate of another question that deals with ternary operator in Objective-C, I feel this difference needs to be addressed.
The ternary operator in PHP has a different associativity than the one in C language (and all others as far as I know). To illustrate this, consider the following example:
$val = "B";
$choice = ( ($val == "A") ? 1 : ($val == "B") ? 2 : ($val == "C") ? 3 : 0 );
echo $choice;
The result of this code (in PHP) will be 3, even though it would seem that 2 should be the correct answer. This is due to weird associativity implementation that threats the upper expression as:
( ( ( ($val=="A") ? 1 : ($val=="B") ) ? 2 : ) ($val=="C") ? 3 : 0 )
▲ ▲ ▲ ▲
| | | |
\ \_____________________________/ /
\_______________________________________/
This is called the ternary operator - have a look here
This basically translates to [statement] ? [true execution path] : [false execution path]
In your case, this would do the following:
if(! empty(self::$settings['tax_value']) )
return self::$settings['tax_value'];
else
return $value;
It is a shorthand if statement. Consider the following code
$Test = true ? 1 : 3;
// test is 1
$Test = false ? 1 : 3;
// test is 3
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What is the PHP ? : operator called and what does it do?
I've been programming PHP for years, but have never understood what this syntax does or means. I'm hoping you guys can explain it to me, it's about time I knew the answer:
list($name, $operator) = (strpos($key, '__')) ? explode('__', $key) : array($key, null);
Specifically, I'm curious about the SOMETHING ? SOMETHING : SOMETHING;
It's shorthand for if() { } else {}.
if($i == 0) {
echo 'hello';
} else {
echo 'byebye';
}
is the same as:
echo $i == 0 ? 'hello' : 'byebye';
The first statement after '?' is executed if the first expression before '?' is true, if not the last is executed. It also evaluates to the value of the executed expression.
Its conditional operator just like if in simple words if in one line
(condition) ? statement1 : statement2
If condition is true then execute statement1 else statement2
this is the pure if else tertiary operation
if(a==b) {
c = 3;
} else {
c = 4;
}
this is same as
c = (a==b) ? 3:4;
I’m trying to shorten my code using the ternary operator.
This is my original code:
if ($type = "recent") {
$OrderType = "sid DESC";
} elseif ($type = "pop") {
$OrderType = "counter DESC";
} else {
$OrderType = "RAND()";
}
How can I use the ternary operator in my code instead of ifs/elses?
$OrderType = ($type = "recent") ? "sid DESC" : "counter DESC" ;
This is the code I tried, but have no idea how to add an “elseif part” to it.
This is called the ternary operator ;-)
You could use two of those :
$OrderType = ($type == 'recent' ? 'sid DESC' : ($type == 'pop' ? 'counter DESC' : 'RAND()'))
This can be read as :
if $type is 'recent'
then use 'sid DESC'
else
if $type is 'pop'
then use 'counter DESC'
else use 'RAND()'
A couple of notes :
You must use == or === ; and not =
The first two ones are comparison operators
The last one is the assignment operator
It's best to use (), to make things easier to read
And you shouldn't use too many ternary operators like that : it makes code a bit hard to understand, i think
And, as a reference about the ternary operator, quoting the Operators section of the PHP manual :
The third group is the ternary
operator: ?:. It should be used
to select between two expressions
depending on a third one, rather than
to select two sentences or paths of
execution. Surrounding ternary
expressions with parentheses is a very
good idea.
I'd suggest using a case statement instead. it makes it a little more readable but more maintainable for when you want to add extra options
switch ($type)
{
case "recent":
$OrderType = "sid DESC";
break;
case "pop":
$OrderType = "counter DESC";
break;
default:
$OrderType = "RAND()";
}