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'] : '';
Related
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']);
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'];
}
Is someone able to explain the meaing of the following statment, and the type of php it is reffering to so I can do further research:
$foo = ($variation_id>0) ? $variation_id : $item_id;
I have tried search but don't really know what i'm searching for.
What I am trying to find out is the name and meaning of the following syntax
? / : and is ($variation_id>0) just a shorthand if statement ?
-- I just stumbled upon conditional variables although a nice simple explanation would still be appreciated.
That structure is called ternary structure and in a short form of If ... Else
Your Snippet:
$foo = ($variation_id>0) ? $variation_id : $item_id;
Converts to
if($variation_id>0) {
$foo = $variation_id;
} else {
$foo = $item_id;
}
Basically, the syntax will come down to something like this
$variable = (<CONDITION>) ? <TRUE EXPRESSION> : <FALSE EXPRESSION>;
You can also combine multiple ternary structure in one line, but it better if you use normal if, if this is over complicated.
That is a ternary condition. If the condition on the left before the '?' is true, it executes the statement after the '?' and before the colon. if not, then it executes the statement after.
In english, this says "use the variation id if it is greater than zero, else use item id"
This is just a shortcut, goes like this:
lets say you have a function.
In the end you want to return a value, but with an exception if the value is 0.
so you will do:
return ($value != 0) ? this_will_be_returned_if_true : this_will_be_returned_if_false;
you can do that also in variable assigning.
Pattern:
(Bool statement) ? true : false;
$foo = ($variation_id>0) ? $variation_id : $item_id;
means
if($variation_id>0)
{
$foo =$variation_id // if true
}
else
{
$foo =$item_id; // if false
}
Let's brake it
$foo=($variation_id>0) ? // This is condition
$variation_id : // This value will be populated by variable '$foo' if condition is true
$item_id; // This value will be populated by variable '$foo' if condition is false
Known as ternary statement/operation, short cut of if else
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 ;
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.