note 78911 modified in language.operators by googleguy

From: Date: Wed, 26 Dec 2012 02:05:43 +0000
Subject: note 78911 modified in language.operators by googleguy
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-192676@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: <?php $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++): <?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' ?> http://php.net/manual/en/language.operators.php

« previous php.notes (#192676) next »