PHP Programming Syntax Question 'x ? x : x;' [duplicate] - php

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;

Related

What's mistake I am doing with this ternary operator? [duplicate]

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' : '-');
}

Confusion about php code

Apologies if this is basic, but I'm learning php.
What does this snippet of code actually do? I've seen it in the source code for a plugin but can't quite figure out what's going on
$_POST['newName'] = $_POST['newName'] == "" ? "Dude" : $_POST['newName'];
Thanks.
This is a short version of if...else. This is a Ternary Logic.
$_POST['newName'] = $_POST['newName'] == "" ? "Dude" : $_POST['newName'];
if $_POST['newName'] == "" is true then "Dude" and else $_POST['newName'].
and both the value will be set in $_POST['newName'].
You can write this like this: [Full form]
if($_POST['newName'] == "")
$_POST['newName'] = "Dude";
The ? is also known as the ternary operator. It is called the ternary operator because it takes three operands - a condition, a result for true, and a result for false. If that sounds like an if statement to you, you are right on the money - the ternary operator is a shorthand (albeit very hard to read) way of doing if statements. Here's an example:
<?php
$agestr = ($age < 16) ? 'child' : 'adult';
?>
First there is a condition ($age < 16), then there is a question mark, and then a true result, a colon, and a false result. If $age is less than 16, $agestr will be set to 'child', otherwise it will be set to 'adult'. That one-liner ternary statement can be expressed in a normal if statement like this:
<?php
if ($age < 16) {
$agestr = 'child';
} else {
$agestr = 'adult';
}
?>
So, in essence, using the ternary operator allows you to compact five lines of code into one, at the expense of some readability.
Sometimes while coding, you might feel that writing an if(...){...}else{...} might feel like overkill for small amounts of code:
$result;
if (20>3)
{
$result = "bigger!";
}
else
{
$result = "smaller!";
}
So for this reason, a short hand notation was created where you would be able to express the exact same statement but without the need for such a big structure:
$result = (20>3) ? "bigger!" : "smaller!" ;
Whatever is between = and ? would then be the condition that is normally between the ( and ) of if(...). If that expression then equates to true, the value obtained by $result would be: "bigger!", and if it equated to false, the result would be: "smaller!".
As Frayne said, it is the shortened version of conditional statement. When we write it in full form, it becomes this:
<?php
if($_POST['newName'] == "") {
$_POST['newName'] = "Dude";
} else {
$_POST['newName'] = $_POST['newName'];
}

ternary operator with ampersand [duplicate]

This question already has answers here:
Can you pass by reference while using the ternary operator?
(5 answers)
Closed 7 years ago.
I use followed somewhere in my code:
if (isset($flat[$pid])) {
$branch = &$flat[$pid]['items'];
} else {
$branch = &$tree;
}
All ok, but when I want to short it to:
$branch = isset($flat[$pid]) ? &$flat[$pid]['items'] : &$tree;
I get:
syntax error, unexpected '&' ...
What I'm doing wrong?
This is because the ternary operator is an expression, so it doesn't evaluate to a variable. And a quote from the manual:
Note: Please note that 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 will work as alternative,
(isset($flat[$pid])) ? ($branch = &$flat[$pid]['items']) : ($branch = &$tree);
Edit:
The shortest it can go will be two lines,
#$temp = &$flat[$pid]['items'];
$branch = &${isset($flat[$pid]) ? "temp" : "tree"};

I came across this sign in PHP " ? 0 : ".What does it mean? [duplicate]

This question already has answers here:
What is ?: in PHP 5.3? [duplicate]
(3 answers)
Closed 8 years ago.
This condition was found in this function:
$kValues = getValueCluster($clusters, $data);
foreach($cPos as $k => $position)
{
$cPos[$k] = empty($kValues[$k]) ? 0 : avg($kValues[$k]);
}
return $cPos
I have been trying to find out what this is. I've searched it in google and it has nothing on it.
... ? ... : ... is a ternary operator. It exists in a lot of languages. It's used like that:
variable = test ? assignIfTrue : assignIfFalse;
In your case, $cPos[$k] will be assigned to 0 if $kValues[$k] is empty and to avg($kValues[$k]) if not.
That's PHP's ternary operator.
Basic example:
$x = true;
$y = $x ? 'true!' : 'false';

Return statement shorthand syntax [duplicate]

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

Categories