note 78911 modified in language.operators by danbrown
| From: | danbrown@php.net | Date: | Fri, 30 Jan 2009 20:39:26 +0000 |
| Subject: | note 78911 modified in language.operators by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-149998@lists.php.net to get a copy of this message | ||
Note that in php the ternary operator ?: has a left associativity unlike in C and C++ where it has
right associativity.
You cannot write code like this (as you may have accustomed to in C/C++):
<?php
$a = 2;
echo (
$a == 1 ? 'one' :
$a == 2 ? 'two' :
$a == 3 ? 'three' :
$a == 4 ? 'four' : 'other');
echo "\n";
// prints 'four'
?>
You need to add brackets to get the results you want:
<?
$a = 2;
echo ($a == 1 ? 'one' :
($a == 2 ? 'two' :
($a == 3 ? 'three' :
($a == 4 ? 'four' : 'other') ) ) );
echo "\n";
//prints 'two'
?>
--was--
Note that in php the ternary operator ?: has a left associativity unlike in C and C++ where it has
right associativity.
You cannot write code like this (as you may have accustomed to in C/C++):
<?
$a = 2;
echo (
$a == 1 ? 'one' :
$a == 2 ? 'two' :
$a == 3 ? 'three' :
$a == 4 ? 'four' : 'other');
echo "\n";
// prints 'four'
?>
You need to add brackets to get the results you want:
<?
$a = 2;
echo ($a == 1 ? 'one' :
($a == 2 ? 'two' :
($a == 3 ? 'three' :
($a == 4 ? 'four' : 'other') ) ) );
echo "\n";
//prints 'two'
?>
http://php.net/manual/en/language.operators.php