Isset ternary operator in php

Currently you're working with the ternary operator:

$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



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:

Chủ Đề