The use of "?" and ":" - php

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

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 is this alternative if/else syntax in PHP called?

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.

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

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;

How to reduce the number of if-else statements in PHP?

I found that there are many if-else statements, especially nested if else statements, these statements make my code less readable. How to reduce the number of if else statements in PHP?
My tips are as follows:
1.Use a switch statement when it is suitable;
2.use exit() statement when it is feasible;
3. Use ternary statement when it is feasible;
Are there other tips that can reduce if else statements, especially nested if-else statements?
Try to use "early return" when possible in order to reduce nesting depth. Try to use boolean expression evaluation.
Example:
function foo($param)
{
$ret = false;
if(userIsLoggedIn()) {
if(is_array($param)) {
if($param['count'] > 0) {
$ret = true;
}
else {
$ret = false;
}
}
}
return $ret;
}
You could rewrite this like:
function foo($param)
{
if(!userIsLoggedIn()) return false;
if(!is_array($param)) return false;
return $param['count'] > 0;
}
Refactor your code into smaller work units. Too much conditional logic is a code-smell and usually indicates that your function needs to be refactored.
There is an official academic method to refactor and simplify a lot of if conditions, called Karnaugh mapping.
It takes in multiple test conditions and attempts to assist in creating simplified if statements that cover all the required cases.
You can learn more about it from wiki here.
Use the ternary operator, refactor your code, write a function or a class which does all the necessary if else statements.
I work on a lot of code thats full of ever evolving business logic and needs to be modified every other day. Two tips that's certainly helped me keep up with the modifications are: avoid all else statements and return/exit as soon as possible. Never get into deep nesting -> create sub routines/functions.
Replacing all else statements with negated if statements makes your code much easier to read top to bottom (the proximity of the condtion and the code block):
# business logic block
if ( $condition ) {
# do something
# code code code
} else {
# code code code
return;
}
# refactored:
if ( ! $contition ) {
# code code code
return;
}
if ( $condition ) {
# code code code
}
Secondly, return/exit as soon as possible. My opinion of course, but I don't see the point in running through any extra conditions/tests when once you've already determined the result of the subroutine, especially when you would like to read the code top to bottom. Removing all ambiguity makes things simpler.
To conclude, I like to avoid using else especially in long lists of BL. Return as soon as you know the result. If the nesting level is more than 2, create sub routines/functions.
polymorphism could get rid of a few as well, allthough harder to implement to reduce if/else in PHP as it is not type safe...
You can reduce the number of if/else codes by using ternary operator or null coalescing operator like this:
Using the ternary operator:
Variable = (Condition) ? (Statement1) : (Statement2);
$age = 20;
print ($age >= 18) ? "Adult" : "Not Adult";
Output:
Adult
By using the null coalescing operator:
// fetch the value of $_GET['user'] and returns 'not passed'
// if username is not passed
$username = $_GET['username'] ?? 'not passed';
print($username);
print("<br/>");
// Equivalent code using ternary operator
$username = isset($_GET['username']) ? $_GET['username'] : 'not passed';
print($username);
print("<br/>");
// Chaining ?? operation
$username = $_GET['username'] ?? $_POST['username'] ?? 'not passed';
print($username);
Output:
not passed
not passed
not passed

Categories