What is this PHP Syntax: ($variation_id>0) ? $variation_id : $item_id; - php

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

Related

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

Reuse function result in shorthand if statement

Is there a way, without declaring a variable to hold the function's result, to use the result of the function called in a shorthand if statement, like:
!empty(getType($user)) ? <RESULT OF FUNCTION> : ''
Rather than doing:
!empty(getType($user)) ? getType($user) : ''
Which effectively calls the function twice.
Simply assign the return value of your function to a variable, e.g.
!empty($result = getType($user)) ? $result : ''
//^^^^^^^^^^ ^^^^^^^ See here
EDIT:
Since gettype() always returns a string, you can just do the following, but then the ternary wouldn't make sense, since it always returns a string.
getType($user)?: ''
It's ugly, but
php > echo (empty($foo = 0)) ? $foo : 'false';
0
Since the result of an assignment operation in PHP is the value being assigned, you get $foo defined, then can use it later for the true clause.

understading the ternary operator in php

I'm reading someone else's code and they have a line like this:
$_REQUEST[LINKEDIN::_GET_TYPE] = (isset($_REQUEST[LINKEDIN::_GET_TYPE])) ? $_REQUEST[LINKEDIN::_GET_TYPE] : '';
I just want to make sure I follow this. I might have finally figured out the logic of it.
Is this correct?
If $_REQUEST[LINKEDIN::_GET_TYPE] is set, then assign it to itself. (meant as a do-nothing condition) otherwise set it to a null string. (Would imply that NULL (undefined) and "" would not be treated the same in some other part of the script.)
The ternary operator you posted acts like a single line if-else as follows
if (isset($_REQUEST[LINKEDIN::_GET_TYPE])) {
$_REQUEST[LINKEDIN::_GET_TYPE] = $_REQUEST[LINKEDIN::_GET_TYPE];
} else {
$_REQUEST[LINKEDIN::_GET_TYPE] = '';
}
Which you could simplify as
if (!(isset($_REQUEST[LINKEDIN::_GET_TYPE]))) {
$_REQUEST[LINKEDIN::_GET_TYPE] = '';
}
You missed the last part. If $_REQUEST[LINKEDIN::_GET_TYPE] is not set, then $_REQUEST[LINKEDIN::_GET_TYPE] is set to empty, not null. The point is that when $_REQUEST[LINKEDIN::_GET_TYPE] is called, that it exists but has no value.
Think of it this way
if(condition) { (?)
//TRUE
} else { (:)
//FALSE
}
So,
echo condition ? TRUE : FALSE;
if that makes sense
This
$foo = $bar ? 'baz' : 'qux';
is the functional equivalent of
if ($bar) { // test $bar for truthiness
$foo = 'baz';
} else {
$foo = 'qux';
}
So yes, what you're doing would work. However, with the newer PHP versions, there's a shortcut version of the tenary:
$foo = $bar ?: 'qux';
which will do exactly what you want
Your explanation is correct as far as my knowledge goes.
A ternary operator is like an if statement. The one you have would look like this as an if statement:
if( isset($_REQUEST[LINKEDIN::_GET_TYPE] ) {
$_REQUEST['LINKEDIN::_GET_TYPE] = $_REQUEST['LINKEDIN::_GET_TYPE];
} else {
$_REQUEST['LINKEDIN::_GET_TYPE] = ''; // It equals an empty string, not null.
}
Sometimes its easier to look at a ternary statement like a normal if statement if you are unsure on what is going on.
The statement you have seems to be doing what you say, setting the value to its self if it is set, and if it is not set, setting it to an empty string.

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

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