PHP is interpreting its expression as true, because non-empty string ( true
) is evaluated as true and concatenated with something (return of is_array()
) that makes no difference, see in the second example. >
Example 1 - string setting the result to true.
$var = 123;
echo "valor de var: ". is_array($var) ? implode("-", $var) : $var); //executa o implode()
^ ^
| |
inicio expressão fim da expressão
Example 2 - Same thing as the first
var_dump((bool)"valor de var: ". false); //string(1) "1"
echo "valor de var: ". false ? implode("-", $var) : $var; //executa o implode() ...
Example 3 - String evaluated as false
var_dump((bool)"0". false);// string(0) ""
echo "0". is_array($var) ? implode("-", $var) : $var;
echo "0". false ? implode("-", $var) : $var;
Example 4 - expected result
If you really want to use the ternary with echo, add parentheses to it, so that piece will be parsed first. The idela is do not use the echo and leave the ternario alone.
echo 'valor de var: '.(is_array($var)? implode('-',$var) : $var);
$var = is_array($var) ? implode('-',$var) : $var;
echo 'valor de var: '. (is_array($var)? implode('-',$var) : $var);
^ ^ ^ ^
|Segunda parte | | Essa parte é processada primeiro |
It's worth remembering PHP uses left side assignment to evaluate ternary instructions.
PHP defines some values that will be interpreted as false
, what is outside the list below is considered true
.
the boolean FALSE itself
the integer 0 (zero)
the float 0.0 (zero)
the empty string, and the string "0"
an array with zero elements
an object with zero member variables (PHP 4 only)
the special type NULL (including unset variables)
SimpleXML objects created from empty tags
Recommended reading:
Manual - boolean
Manual - ternary comparison
Manual - Operator Precedence
SOen - Understanding nested PHP ternary operator
SOen - PHP ternary operator not working as expected