Using nested ternary operators [duplicate] - php

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.

Related

How to write this conditional statements with ternary operators

I want to check if the usr_name of user is empty, then get his email and adjust a new variable to it.
So here is the traditional way:
if(auth()->user()->usr_name != null){
$user_input = auth()->user()->usr_name;
}else{
$user_input = auth()->user()->usr_email;
}
Now I want to write this with ternary condition operators, so I tried this:
$user_input = empty(auth()->user()->usr_name) ? auth()->user()->usr_name : auth()->user()->usr_email;
But this is wrong, since it returns null for $user_input.
So what is the correct way of writing this with ternary operators?
$user_input = auth()->user()->usr_name ?: auth()->user()->usr_email;
Ternary operator has a short syntax in PHP. The above code is the same as
if (auth()->user()->usr_name) {
$user_input = auth()->user()->usr_name;
} else {
$user_input = auth()->user()->usr_email;
}
Which is most likely equivalent to your code, considering the non strict != null check.
Tenary operator check the result before "?" and if true returns first pair distinguished with ":" if not return second pair.
Let say A = true
C = A ? 1: 2 ;
here C equals to 1
In your example you must changed order of tenary result values
$user_input = empty(auth()->user()->usr_name) ?auth()->user()->usr_email : auth()->user()->usr_name
You just have your logic back to front
$user_input = empty(auth()->user()->usr_name) ? auth()->user()->usr_email : auth()->user()->usr_name;
So to be clear, you are giving priority to usr_name if it is set, otherwise use the usr_email
Note that you could put this in an accessor and then call something like auth()->user()->identifier anywhere in your project
If you use PHP >= 7.0 you could use the null-coalescing operator to write a really beautiful statement instead.
It would look something like:
$user_input = auth()->user()->usr_name ?? auth()->user()->usr_email;

What means this line? [duplicate]

This question already has answers here:
How to replace "if" statement with a ternary operator ( ? : )?
(16 answers)
Closed 3 years ago.
$n = isset($_GET["n"]) ? $_GET['n'] : '';
I find this "method" to avoid errors before insert stuff in the input type.. and it works.. but I would like a detailed explanation of this line. Thank you!
This is called the ternary operator shorthand of if...else
(condition) ? true : false
There is a condition which has been checked on left, if its true the statement after the ? will be execute else the statement after the : will execute.
It's called Ternary operator
The ternary operator is a shorthand for the if {} else {} structure. Instead of writing this:
if ($condition) {
$result = 'foo'
} else {
$result = 'bar'
}
You can write this:
$result = $condition ? 'foo' : 'bar';
If this $condition evaluates to true, the lefthand operand will be assigned to $result. If the condition evaluates to false, the righthand will be used.
In your case
If the value of $_GET["n"] isset then it'll take $_GET["n"] value.
if the value is not set then it'll take ('') value.
$n = isset($_GET["n"]) ? $_GET['n'] : '';

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']);

Just need to understand a PHP Syntax used to set POSTed var [duplicate]

This question already has answers here:
What is ?: in PHP 5.3? [duplicate]
(3 answers)
Closed 8 years ago.
So I'm using the following php code to set variables that are received from a POST method, but I'm interested in how it works.
$var1 = isset($_REQUEST['var1']) ? $_REQUEST['var1'] : 'default';
I understand what it does, but I don't understand the syntax.
Thanks for the help :)
? is just a short and optimised notation of doing this:
if (isset($_REQUEST["var1"])) // If the element "var1" exists in the $_REQUEST array
$var1 = $_REQUEST["var1"]; // take the value of it
else
$var1 = "default"; // if it doesn't exist, use a default value
Note that you might want to use the $_POST array instead of the $_REQUEST array.
This is a short hand IF statement and from that you are assigning a value to $var1
The syntax is :
$var = (CONDITION) ? (VALUE IF TRUE) : (VALUE IF FALSE);
You probably mean ternary operator
Syntax it's same like
if(isset($_REQUEST('var1') ) {
$var1 = ? $_REQUEST('var1')
}else {
$var1 =: 'default';
}
It's the synatx of the ternary operator. It's shorthand for if/else. Please read PHP Manaul
This is a 'ternary operator', what it says is:-
If var1 is set as a post variable then set var1 to that value, otherwise setvar1 to be the string 'default'. Using traditional syntax it would be:-
if (isset($_REQUEST('var1')) { $var1 = $_REQUEST('var1'); } else { $var1 = 'default'; }
its a short way of doing an if. if you are expecting a post variable its must better to use _POST rather than request.
the "?" says if the isset($_REQUEST) is true, then do the everything between the ? and : otherwise do everything between the : and the ;

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

Categories