What is this alternative if/else syntax in PHP called? - php

What is the name of the following type of if/else syntax:
print $foo = ($hour < 12) ? "Good morning!" : "Good afternoon!";
I couldn't find any dedicated page in the php manual. I knew that it existed, because I've read a book (last year) with it, and now I found this post.

This is called a ternary expression
http://php.net/manual/en/language.expressions.php
You should note, this is not an "alternate syntax for if" as it should not be used to control the flow of a program.
In the simple example of setting variables, it can help you avoid lengthy if statements like this: (ref: php docs)
// Example usage for: Ternary Operator
$action = (empty($_POST['action'])) ? 'default' : $_POST['action'];
// The above is identical to this if/else statement
if (empty($_POST['action'])) {
$action = 'default';
} else {
$action = $_POST['action'];
}
However it can be used other places than just simple variable assignent
function say($a, $b) {
echo "{$a} {$b}";
}
$foo = false;
say('hello', $foo ? 'world' : 'planet');
//=> hello planet

It's called the ternary operator - although many people call it the "?: operator" because "ternary" is such a seldom-used word.

Related

isset PHP isset($_GET['something']) ? $_GET['something'] : ''

I am looking to expand on my PHP knowledge, and I came across something I am not sure what it is or how to even search for it. I am looking at php.net isset code, and I see isset($_GET['something']) ? $_GET['something'] : ''
I understand normal isset operations, such as if(isset($_GET['something']){ If something is exists, then it is set and we will do something } but I don't understand the ?, repeating the get again, the : or the ''. Can someone help break this down for me or at least point me in the right direction?
It's commonly referred to as 'shorthand' or the Ternary Operator.
$test = isset($_GET['something']) ? $_GET['something'] : '';
means
if(isset($_GET['something'])) {
$test = $_GET['something'];
} else {
$test = '';
}
To break it down:
$test = ... // assign variable
isset(...) // test
? ... // if test is true, do ... (equivalent to if)
: ... // otherwise... (equivalent to else)
Or...
// test --v
if(isset(...)) { // if test is true, do ... (equivalent to ?)
$test = // assign variable
} else { // otherwise... (equivalent to :)
In PHP 7 you can write it even shorter:
$age = $_GET['age'] ?? 27;
This means that the $age variable will be set to the age parameter if it is provided in the URL, or it will default to 27.
See all new features of PHP 7.
That's called a ternary operator and it's mainly used in place of an if-else statement.
In the example you gave it can be used to retrieve a value from an array given isset returns true
isset($_GET['something']) ? $_GET['something'] : ''
is equivalent to
if (isset($_GET['something'])) {
echo "Your error message!";
} else {
$test = $_GET['something'];
}
echo $test;
Of course it's not much use unless you assign it to something, and possibly even assign a default value for a user submitted value.
$username = isset($_GET['username']) ? $_GET['username'] : 'anonymous'
You have encountered the ternary operator. It's purpose is that of a basic if-else statement. The following pieces of code do the same thing.
Ternary:
$something = isset($_GET['something']) ? $_GET['something'] : "failed";
If-else:
if (isset($_GET['something'])) {
$something = $_GET['something'];
} else {
$something = "failed";
}
It is called the ternary operator. It is shorthand for an if-else block. See here for an example http://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary
? is called Ternary (conditional) operator : example
What you're looking at is called a Ternary Operator, and you can find the PHP implementation here. It's an if else statement.
if (isset($_GET['something']) == true) {
thing = isset($_GET['something']);
} else {
thing = "";
}
If you want an empty string default then a preferred way is one of these (depending on your need):
$str_value = strval($_GET['something']);
$trimmed_value = trim($_GET['something']);
$int_value = intval($_GET['somenumber']);
If the url parameter something doesn't exist in the url then $_GET['something'] will return null
strval($_GET['something']) -> strval(null) -> ""
and your variable $value is set to an empty string.
trim() might be prefered over strval() depending on code (e.g. a Name parameter might want to use it)
intval() if only numeric values are expected and the default is zero. intval(null) -> 0
Cases to consider:
...&something=value1&key2=value2 (typical)
...&key2=value2 (parameter missing from url $_GET will return null for it)
...&something=+++&key2=value (parameter is " ")
Why this is a preferred approach:
It fits neatly on one line and is clear what's going on.
It's readable than $value = isset($_GET['something']) ? $_GET['something'] : '';
Lower risk of copy/paste mistake or a typo: $value=isset($_GET['something'])?$_GET['somthing']:'';
It's compatible with older and newer php.
Update
Strict mode may require something like this:
$str_value = strval(#$_GET['something']);
$trimmed_value = trim(#$_GET['something']);
$int_value = intval(#$_GET['somenumber']);

error object and array

I have this code
$myvar = is_object($somevar) ? $somevar->value : is_array($somevar) ? $somevar['value'] : '';
issue is that sometime I am getting this error
PHP Error: Cannot use object of type \mypath\method as array in /var/www/htdocs/website/app/resources/tmp/cache/templates/template_view.html.php on line 988
line 988 is the above line I included. I am already checking if its object or array, so why this error then?
It has something to do with priority, or the way PHP is evaluating your expression. Grouping with parentheses solves the problem:
$myvar = is_object($somevar) ? $somevar->value : (is_array($somevar) ? $somevar['value'] : '');
See the notes here: http://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary
Note:
It is recommended that you avoid "stacking" ternary expressions. PHP's
behaviour when using more than one ternary operator within a single
statement is non-obvious:
Example #3 Non-obvious Ternary Behaviour
<?php
// on first glance, the following appears to output 'true'
echo (true?'true':false?'t':'f');
// however, the actual output of the above is 't'
// this is because ternary expressions are evaluated from left to right
// the following is a more obvious version of the same code as above
echo ((true ? 'true' : false) ? 't' : 'f');
// here, you can see that the first expression is evaluated to 'true', which
// in turn evaluates to (bool)true, thus returning the true branch of the
// second ternary expression.
?>
You need to place parenthesis around the second ternary:
$myvar = is_object($somevar) ? $somevar->value : (is_array($somevar) ? $somevar['value'] : '');
This must have something to do with operator precedence, though I'm not sure why yet.
Opinion: The ternary with or without parenthesis is difficult to read IMHO. I'd stick with the expanded form:
$myvar = '';
if(is_object($somevar)) {
$myvar = $somevar->value;
} elseif(is_array($somevar)) {
$myvar = $somevar['value'];
}

The use of "?" and ":"

I've read through a lot of code where they have if statements, i've noticed other languages use this to. Asp being one.
Tried googling but couldn't find a answer for it.
What exactly does ?: stand for and when to use it.
As far as I'm aware ? is equal to if() and : being equal to }else{.
It is the ternary operator (although in most languages it is better-named as the "conditional operator").
People will often erroneously refer to it as "shorthand if/else". But this is a misnomer; if/else is a statement, ?: is an expression. In most languages, these are distinct concepts, with different semantics.
This is called ternary operator.
It is meant to simplify code in some cases. Consider this:
var str;
if(some_condition)
str = 'yes';
else
str = 'no';
This can be easily rewritten as
var str = some_condition ? 'yes' : 'no';
Your assumption is right.
It is a Ternary operation (Wikipedia)
Essentially, the syntax is condition ? then-expession : else-expression. Typically it is used in assigning variables:
varname = something == 123 ? "yes" : "no";
But it can be used pretty much anywhere in place of a value. It's mostly useful for avoiding repetitive code:
if( something == 123) {
varname = "yes";
}
else {
varname = "no";
}
You could read the documentation. The section you're looking for is titled "Ternary Operator".
You can express calculations that might otherwise require an if-else construction more concisely by using the conditional operator. For example, the following code uses first an if statement and then a conditional operator to check for a possible division-by-zero error before calculating the sin function.
if(x != 0.0) s = Math.Sin(x)/x; else s = 1.0;
s = x != 0.0 ? Math.Sin(x)/x : 1.0;
from http://msdn.microsoft.com/en-us/library/ty67wk28(v=vs.90).aspx
In Java, it's an if/else relationship.
An example of a ternary operation:
boolean bool = (x==1) ? true : false;
http://en.wikipedia.org/wiki/Ternary_operation

Using nested ternary operators [duplicate]

This question already has answers here:
Stacking Multiple Ternary Operators in PHP
(11 answers)
Closed 2 years ago.
I've been trying to use isset() in nested form like below:
isset($_POST['selectedTemplate'])?$_POST['selectedTemplate']:isset($_GET['selectedTemplate'])?$_GET['selectedTemplate']:0
But seems I'm missing something. Can anyone assist me how to do it?
Wrap it in parentheses:
$selectedTemplate = isset($_POST['selectedTemplate'])
? $_POST['selectedTemplate']
: (
isset($_GET['selectedTemplate'])
? $_GET['selectedTemplate']
: 0
);
Or even better, use a proper if/else statement (for maintainability):
$selectTemplate = 0;
if (isset($_POST['selectedTemplate'])) {
$selectTemplate = $_POST['selectedTemplate'];
} elseif (isset($_GET['selectedTemplate'])) {
$selectTemplate = $_GET['selectedTemplate'];
}
However, as others have pointed out: it would simply be easier for you to use $_REQUEST:
$selectedTemplate = isset($_REQUEST['selectedTemplate'])
? $_REQUEST['selectedTemplate']
: 0;
As of PHP 7 we can use Null coalescing operator
$selectedTemplate = $_POST['selectedTemplate'] ?? $_GET['selectedTemplate'] ?? 0;
A little investigate here, and I guess, I've found real answer :)
Example code:
<?php
$test = array();
$test['a'] = "value";
var_dump(
isset($test['a'])
? $test['a']
: isset($test['b'])
? $test['b']
: "default"
);
Be attentive to round brackets, that I've put.
I guess, you're waiting to get similar behavior:
var_dump(
isset($test['a'])
? $test['a']
: (isset($test['b']) // <-- here
? $test['b']
: "default") // <-- and here
);
But! Real behavior looks like this:
var_dump(
(isset($test['a']) // <-- here
? $test['a']
: isset($test['b'])) // <-- and here
? $test['b']
: "default"
);
General mistake was, that you've missed notice: Undefined index.
Online shell.
It's simpler to read if we write ternary in the following manner:
$myvar = ($x == $y)
?(($x == $z)?'both':'foo')
:(($x == $z)?'bar':'none');
But ternary operators are short, effective ways to write simple if statements. They are not built for nesting. :)
You might have an easier time simply using the $_REQUEST variables:
"$_REQUEST is an associative array that by default contains the contents of $_GET, $_POST and $_COOKIE."
http://us2.php.net/manual/en/reserved.variables.request.php
I believe this will work:
$test = array();
$test['a'] = 123;
$test['b'] = NULL;
$var = (isset($test['a']) ? $test['a'] : (!isnull($test['b']) ? $test['b'] : "default"));
echo $var;
Instead of the ternary with the ambiguous precedence, you could just use $_REQUEST instead of the fiddly $_GET and $_POST probing:
isset($_REQUEST['selectedTemplate']) ? $_REQUEST['selectedTemplate'] : 0
This is precisely what it is for.

how to write this conditions in php

hey guys , im writing a class and im wondering how i can write a condition statement in this way :
$this->referer= (!empty($_SERVER['HTTP_REFERER'])) ? htmlspecialchars((string) $_SERVER['HTTP_REFERER']) : '';
i need to find my user_id and this is the usual condtion :
if(is_user($user)){
$cookie=cookiedecode($user);
$user_id=intval($cookie[0]);
}
and i think it should be something like this :
$this->user_id = (is_user($user)) ? (cookiedecode($user)) : $cookie[0];
but it didnt work
what about this way :
if(is_user($user)){
$cookie=cookiedecode($user);
$this->user_id =intval($cookie[0]);
}
The ternary operator should be used sparingly, and only when the logic is simple enough to maintain readability! Get too complex and the shorthand outweighs its usefulness by being difficult to understand.
The ternary operator will only work with one variable assignement at a time. Here is the manual example
<?php
// Example usage for: Ternary Operator
$action = (empty($_POST['action'])) ? 'default' : $_POST['action'];
// The above is identical to this if/else statement
if (empty($_POST['action'])) {
$action = 'default';
} else {
$action = $_POST['action'];
}
Your example
$this->user_id = (is_user($user)) ? (cookiedecode($user)) : $cookie[0];
will assign the user_id to cookiedecode($user) if is_user() returns true, or to $cookie[0] if not.
In light of this:
you should keep your existing code structure!!
if(is_user($user)){
$cookie=cookiedecode($user);
$this->user_id =intval($cookie[0]);
}
I didn't see any ELSE statement in your code and i don't understand on why do you want to use short form of conditional statement.

Categories