Sinthia V
Sinthia V

Reputation: 2093

Omitting the second part of the ternary operator

Given the following expression:

$att['menutext'] = isset($attrib_in['i_menu_text']) ? : $this->getID();

If it evaluates to true, will $att['menutext'] be set to true or $this->getID()?

Upvotes: 10

Views: 2833

Answers (5)

Jim H.
Jim H.

Reputation: 5579

Yes, in version 5.3+ the middle expression is optional and returns true.

$a = (true ? : 1); // $a evaluates to true.
$a = (false ? : 1); // $a evaluates to 1.

Upvotes: 3

Puggan Se
Puggan Se

Reputation: 5846

never tested before, but its quite easy to test:

<?php var_dump(TRUE ? : 'F'); ?>

and its says: bool(true)

Upvotes: 1

Keith Thompson
Keith Thompson

Reputation: 263497

According to this reference:

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.

Upvotes: 15

nickb
nickb

Reputation: 59709

This won't execute, it's invalid syntax for PHP < 5.3.

Parse error: syntax error, unexpected ':' on line X

If you want the value to be set to true, then use true:

$att['menutext'] = isset($attrib_in['i_menu_text']) ? true : $this->getID();

Or it may be more likely that you want:

$att['menutext'] = isset($attrib_in['i_menu_text']) ? $attrib_in['i_menu_text'] : $this->getID();

Upvotes: 0

Simone
Simone

Reputation: 21272

It's just the same as the following

$att['menutext'] = isset($attrib_in['i_menu_text']) ? true : $this->getID();

Upvotes: 2

Related Questions