Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Ternary Operator checking if variable contains something?

Tags:

php

Consider the following (simplified to the bare bones):

abstract class Validator {    

    public function __construct($data = null)
    {
        $this->data = $data ?: Input::all();
    }
}


$validation = new PageValidator($data);

'Input::all' is returning an array. $data is also an array.

The bit I am struggling with is:

$this->data = $data ?: Input::all();

I think it is essentially doing this:

    if(!$data) {
        $this->data = Input::all();
    } else {
        $this->data = $data;
    };

But I don't really understand how?

like image 600
dopey Avatar asked Aug 02 '13 19:08

dopey


People also ask

How use ternary operator in if condition in PHP?

It is called a ternary operator because it takes three operands- a condition, a result statement for true, and a result statement for false. The syntax for the ternary operator is as follows. Syntax: (Condition) ? (Statement1) : (Statement2);

What is !== In PHP?

” and “==!” in PHP. !== Operator: It is called as non-identical operator. It returns true if operands are not equal, or they are not of the same type.

Is ternary operator faster than if in PHP?

Most of the time, they are about the same speed and you don't need to care.

What are the three arguments of a ternary operator?

The ternary operator take three arguments: The first is a comparison argument. The second is the result upon a true comparison. The third is the result upon a false comparison.


2 Answers

It's a feature of PHP 5.3 and above:

The ternary operator now has a shorthand form: ?:.

like image 65
federico-t Avatar answered Sep 18 '22 02:09

federico-t


Your understanding of the ternary operator is correct.

The exact syntax you've shown that omits the middle part of the operator was a feature added in PHP 5.3:

Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

The full expression, without omission, is:

$this->data = $data ? $data : Input::all();

Which translates to what you've assumed:

if($data) {
    $this->data = $data;
} else {
    $this->data = Input::all();
}
like image 27
newfurniturey Avatar answered Sep 22 '22 02:09

newfurniturey