Hướng dẫn short if php

Update for PHP 7 (thanks shock_gone_wild)

Nội dung chính

  • PHP Ternary Operator
  • Ternary Syntax
  • PHP Ternary Operator Example
  • PHP Ternary Operator with Isset() Example
  • PHP Null Coalescing Operator
  • PHP Null Coalescing Operator Example
  • PHP Null Coalescing Operator Nesting Example
  • What is Ternary operator?
  • When do we use Ternary Operator?
  • Advantages of Ternary Operator
  • Ternary shorthand
  • Null Coalescing Operator
  • How use isset with ternary operator in PHP?
  • What is the ternary operator in PHP?
  • What is isset ($_ GET in PHP?
  • Is NULL ternary operator PHP?

PHP 7 introduces the null coalescing operator which simplifies the below statements to:

$var = $var ?? "default";

Before PHP 7

No, there is no special operator or special syntax for this. However, you could use the ternary operator:

$var = isset($var) ? $var : "default";

Or like this:

isset($var) ?: $var = 'default';

Currently you're working with the ternary operator:

Nội dung chính

  • PHP Ternary Operator
  • Ternary Syntax
  • PHP Ternary Operator Example
  • PHP Ternary Operator with Isset() Example
  • PHP Null Coalescing Operator
  • PHP Null Coalescing Operator Example
  • PHP Null Coalescing Operator Nesting Example
  • What is Ternary operator?
  • When do we use Ternary Operator?
  • Advantages of Ternary Operator
  • Ternary shorthand
  • Null Coalescing Operator
  • How use isset with ternary operator in PHP?
  • What is the ternary operator in PHP?
  • What is isset ($_ GET in PHP?
  • Is NULL ternary operator PHP?
$friendid = (!isset($_GET['friendid'])) ? $_GET['friendid'] : 'empty';

Break it down to an if-else statement and it looks like this:

if(!isset($_GET['friendid']))
   $friendid = $_GET['friendid'];
else
   $friendid = 'empty';

Look at what's really happening in the if statement:

!isset($_GET['friendid'])

Note the exclamation mark (!) in front of the isset function. It's another way to say, "the opposite of". What you're doing here is checking that there is no value already set in $_GET['friendid']. And if so, $friendid should take on that value.

But really, it would break since $_GET['friendid'] doesn't even exist. And you can't take the value of something that isn't there.

Taking it from the start, you have set a value for $_GET['friendid'], so that first if condition is now false and passes it on to the else option.

In this case, set the value of the $friendid variable to empty.

What you want is to remove the exclamation and then the value of $friendid will take on the value of $_GET['friendid'] if it has been previously set.

PHP has two special shorthand conditional operators.

  • Ternary Operator
  • Null Coalescing Operator

PHP Ternary Operator

The ternary operator is a short way of performing an if conditional.

Ternary Syntax

() ? () : ()

  • If the condition is true, the result of on true expression is returned.
  • If the condition is false, the result of on false expression is returned.
  • Since PHP 5.3, you can omit the on true expression. (condition) ?: (on false) returns the result of condition if the condition is true. Otherwise, the result of on false expression is returned.

PHP Ternary Operator Example


'; // hello hyvor, because $username returns true

$username = null;
echo 'Hello ' . ($username ?: 'Guest') . '
'; // hello guest, because $username returns null // another example $var = 5; $isGreaterThan2 = $var > 2 ? true : false; var_dump($isGreaterThan2);

Run Example ››

It is not recommended to use nested expressions with the ternary operator. PHP's behavior when using more than one ternary operator within a single statement is non-obvious. So, use ternary operator only for simple conditions.

The ternary operator is commonly used with isset() function in PHP.

PHP Ternary Operator with Isset() Example


';

$fisrtname = 'Hyvor';
$lastname = 'Developer';
$username = (isset($fisrtname, $lastname)) ? $fisrtname . ' ' . $lastname : "Guest";
echo $username;

Run Example ››

Tip: The isset() function returns true if the variables (which are sent to the function in parameters) are set and not null.

Wrapping the expressions in the ternary operator with parentheses is optional.

PHP Null Coalescing Operator

PHP's null coalescing operator is a useful new feature which was introduced in PHP 7.

The null coalescing operator can be used to assign default values to a variable.

In the example below, the null coalescing expression returns 2 because $a is not defined.

PHP Null Coalescing Operator Example


Run Example ››

Important: Null coalescing operator allows for nesting.

PHP Null Coalescing Operator Nesting Example


Run Example ››

Using the if-else and switch case is an essential part of programming for evaluating conditions. We always look for shortcuts everywhere whether it is a route for traveling or game or code. In this Ternary Operator PHP, we will see how it is used for shortening conditional statements.

What is Ternary operator?

The ternary operator is a conditional operator that decreases the length of code while performing comparisons and conditionals. This method is an alternative for using if-else and nested if-else statements. The order of execution for this operator is from left to right. Obviously, it is the best case for a time-saving option.

It also produces an e-notice while encountering a void value with its conditionals. It is called a ternary operator because it takes three operands – a condition, a result for true, and a result for false.

Syntax:

(Condition) ? (Statement1) : (Statement2);
  • Condition: It is the expression to be evaluated which returns a boolean value.
  • Statement 1: it is the statement to be executed if the condition results in a true state.
  • Statement 2: It is the statement to be executed if the condition results in a false state.

Example program to whether student is pass or fail:

=40) ? "pass" : "Fail";
?>

Output:

pass

When do we use Ternary Operator?

We use ternary operator when we need to simplify if-else statements that are used to assign values to variables. Moreover, it is commonly used when we assign post data or validate forms.

Let’s say, we were programming a login form for a college university where we wanted to ensure that the user entered their registration number provided by the university then we could move further.

//if the registration number is not specified, notify the customer
$reg_number = (isset($_POST['reg'])) ? $_POST['reg'] : die('Please enter your registration number');

Let’s look at an example of a validation form for better understanding:



In order to get the values of our text fields, we can use the following code:


Advantages of Ternary Operator

  • It will make the code shorter
  • It will make the code more readable
  • The code becomes simpler

Ternary shorthand

Short ternary operator syntax can be used by leaving out the middle part of the ternary operator for quick shorthand evaluation. It is also referred to as Elvis operatory(?

Syntax:

expression1 ?: expression2

Elvis operator can be used in order to reduce redundancy of your conditions and shorten the length of your assignments. It is the ternary operator with the second operand omitted. It will return the first operand if the operand is true else it evaluates and returns its second operand.

$val = $_GET['user'] ?: 'default';

If you use the ternary shorthand operator like this, it will cause notice if

$_GET['user']

is not set, instead of writing some lengthy code like this:

$val = isset($_GET['user']) ? $_GET['user'] : 'default';

Null Coalescing Operator

It replaces the ternary operation in conjunction with isset() function which is used to check whether a given variable is NULL or not and returns its first operand if it exists and is not NULL else it returns the second operand.

Syntax:

(Condition)?(Statement1)?(Statement2);
$user= $_GET['user'] ?? 'nobody';

It will fetch the value of $_GET[user] and returns ‘nobody’ if it does not exist.

Instead of writing some lengthy code like this:

$user= isset($_GET['user']) ? $_GET['user'] : 'nobody';

With this we come to an end of this article, I hope you understood the ternary operator, the purpose and advantages of the ternary operator, Ternary shorthand and Null coalescing Operator.

Got a question for us? Please mention it in the comments section of ”ternary operator in php” and I will get back to you.

Enjoy this post? Give Sayantini a like if it's helpful.

9

Share

A Data Science Enthusiast. Keen to work with technologies like Machine Learning, Artificial Intelligence & Deep Learning. If you ask about Programming Skills : "I don't C, I Python" ;)

Discover and read more posts from Sayantini

Enjoy this post?

Leave a like and comment for Sayantini

How use isset with ternary operator in PHP?

"default-value"; // which is synonymous to: $var = isset($array["key"]) ? $array["key"] : "default-value"; In PHP 5.3+, if all you are checking on is a "truthy" value, you can use the "Elvis operator" (note that this does not check isset).

What is the ternary operator in PHP?

The term "ternary operator" refers to an operator that operates on three operands. An operand is a concept that refers to the parts of an expression that it needs. The ternary operator in PHP is the only one that needs three operands: a condition, a true result, and a false result.

What is isset ($_ GET in PHP?

Definition and Usage The isset() function checks whether a variable is set, which means that it has to be declared and is not NULL. This function returns true if the variable exists and is not NULL, otherwise it returns false.

Is NULL ternary operator PHP?

Ternary Operator throws e-notice if left operand is null, while null coalescing operator does not throws e-notice if left operand does not exist. Ternary Operator checks whether the value is true, but Null coalescing operator checks if the value is not null.