understading the ternary operator in php - 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.

Related

PHP - Assigning a value in IF statement - false if null

I'm trying to simplify some code. I've found that if you assign a value within an if statement, but the value ends up being null, then the evaluated if is FALSE.
Example:
if($myvar = doSomething()) {
echo '$myvar = '.$myvar;
}
else {
echo "was null";
}
function doSomething() {
$a = null;
return $a;
}
The script above will display "was null". However, if $a = 1, then it will display "myvar = 1".
I've tried to find some documentation around this behaviour but haven't been successful. All of my sources are close, but don't describe it well.
My question: Is this expected behaviour? If doSomething() returns null, is what I'm doing equivalent to if(null) {...?
EDIT: YES I mean '=' not '==' in the if statement. What I'm asking is it expected that this should always return false: if($a = null) whereas this returns true if($a = 1)
What you're doing is fully expected. The value of the assignment expression $a=b is the assigned value b. So,
if($myvar = doSomething()) { ...
is equivalent to
$myvar = doSomething();
if ($myvar) { ...
This behavior is completely unrelated to the if statement. The documentation clearly states, in the second paragraph:
The value of an assignment expression is the value assigned. That is, the value of "$a = 3" is 3.
Try to call function in variable.
$getvar = doSomething();
if($myvar == $getvar) {
// stuff
}

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

Shorthand conditional to define a variable based on the existence of another variable in PHP

Essentially, I'd love to be able to define a variable as one thing unless that thing doesn't exist. I swear that somewhere I saw a shorthand conditional that looked something like this:
$var=$_GET["var"] || "default";
But I can't find any documentation to do this right, and honestly it might have been JS or ASP or something where I saw it.
I understand that all that should be happening in the above code is just to check if either statement returns true. But I thought I saw someone do something that essentially defined a default if the first failed. Is this something anyone knows about and can help me? Am I crazy? It just seems redundant to say:
$var=($_GET["var"]) ? $_GET["var"] : "default";
or especially redundant to say:
if ($_GET["var"]) { $var=$_GET["var"]; } else { $var="default"; }
Thoughts?
Matthew has already mentioned the only way to do it in PHP 5.3. Note that you can also chain them:
$a = false ?: false ?: 'A'; // 'A'
This is not the same as:
$a = false || false || 'A'; // true
The reason why is that PHP is like most traditional languages in this aspect. The logical OR always returns true or false. However, in JavaScript, the final expression is used. (In a series of ORs, it will be the first non-false one.)
var a = false || 'A' || false; // 'A'
var b = true && 'A' && 'B'; // 'B';
In such cases you should be checking for existence of the variable in $_GET and then whether it's valid for your parameters. For example:
$var = (isset($_GET["var"]) && $_GET['var'] !== '') ? $_GET["var"] : "default";
However, this can become pretty unreadable pretty quickly. I'd say keep it readable by first initializing your variable to a safe default, and then overwriting that with an external one, if that's valid:
$var = "default";
if (isset($_GET['var') && $_GET['var'] !== '') {
$var = $_GET['var] ;
}
As for your first example, $var=$_GET["var"] || "default"; exists in Javascript: var someVar = incomingVar || "default";
I've always used empty.
$var = !empty($_GET['var'])?$_GET['var']:'default';

How should boolean expressions be written in PHP?

How should the following boolean expression be written in PHP:
$foo = "";
if($var==TRUE){
$foo = "bar";
}
or
if($var==TRUE){
$foo = "bar";
}else{
$foo = "";
}
or
$foo = ($var==TRUE) ? "bar": "";
First off, true is not a constant, it's a token, so please don't uppercase it (I know some standards do that, but I think it confuses the meaning)...
Second, you don't need the redundant $var == true comparison inside the if. It's exactly the same as if ($var) { (For a double == comparison. An identical comparison === would need to be explicit).
Third, I prefer the pre-initialization. So:
$foo = '';
if ($var) {
$foo = 'one status';
} else {
$foo = 'another status';
}
If you don't need the else branch, just remove it. I prefer the pre-initialization since it forces you to initialize the variable, and it prevents cases where you forget to initialize it in one of the branches. Plus, it gives you a type hint when you go back to read the function later...
And for a simple branch like that, using the ternary syntax is fine. If there's more complex logic, I'd stay away though:
$foo = $var ? 'bar' : '';
All of those work. It's preference. I'd consider initializing the variable first like you do in the 1st example. But for something this simple, the 3rd option is fine in my book.
Also, the 3rd doesn't have to be so verbose if $var is just a boolean value:
$foo = $var ? "bar" : "";
I like the first one:
$foo = "";
if($var==TRUE){
$foo = "bar";
}
Since it is clear, concise, and easy to read.
I prefer the first one (except for the redundant test for the boolean) because it works consistently across languages, particularly those requiring to declare the variable (and maybe typify it) ahead of setting it.
Java:
String foo = "";
if (var) {
foo = "Something";
}
JavaScript or JavaFX:
var foo = "";
if (var) {
foo = "Something";
}
Etc.
One can use the 3rd form too but if the condition (or assignment) is complex, it is a bit less readable.
Doesn't matter very much. I like the first one when there's a lot of elseif's so that you know the variable is always initialized. But it's really just a matter of preference.
Like the quotes, I like using single ones in php. No good reason :)
The right answer, as it often is the case is, "it depends". In this case,
if ($var==TRUE) $foo = "bar";
else $foo = "";
is very clear. But what is your context?
In general, the tertiary operator, your third option, should be used with extreme caution, as it very easily becomes hard to read.
But think in terms of what you want your code to MEAN, more than about what it DOES. Do you want to set your $foo to a "normal" value and then override it? Or do you want to set to something that depends on what $var is?
Something I find useful to change, that is not directly what you ask, but that is similar, is this, from
function func() {
...
if ($condition) {
do plenty
of things
}
else {
do plenty
of things
}
}
That, I generally like to change to:
function func() {
...
if ($condition) {
do plenty
of things
return;
}
do plenty
of things
}
It generally makes sense.
Just ask yourself: "If someone who didn't know anything about my code read it, would it make sense to him? Or her?"

What is this syntax in PHP?

I'm working on modifying a script to better suit my needs, and I came across this line in the code:
return isset($_COOKIE[$parameter_name]) ? $_COOKIE[$parameter_name] : "";
I know that the function itself is essentially a cookie getter method, but I'm not quite sure what that syntax (i.e. the "?" and ":") means. I apologize if this is a really dumb question, but could someone explain it to me?
It's a ternary operation and is basically a more compact way of writing an if/then/else.
So in your code sample it's being used instead of having to write:
if (isset($_COOKIE[$parameter_name])) {
return $_COOKIE[$parameter_name];
} else {
return "";
}
It's a ternary operation which is not PHP specific and exists in most langauges.
(condition) ? true_case : false_case
And in my opinion should only be used as short one liners like in your example. Otherwise readabilty would suffer – so never nest ternary operation (though it's possible to do so).
The ? : are the ternary operator. Its a very quick if a then b else c:
if (a) { return b; } else { return c; }
is equivalent to:
return a ? b : c;
return isset($_COOKIE[$parameter_name]) ? $_COOKIE[$parameter_name] : "";
The function return:
$_COOKIE[$parameter_name]
If $_COOKIe with specified parameter_name exists, empty string otherwise.
Prototype:
condition ? this runs if condition true : this runs if condition false;

Categories