PHP is interpreting its expression as true, because string is not empty(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 suit with echo, add parentheses to it, so that piece will be analyzed first. The idea is not to use echo and leave the suit 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 |
Remember PHP uses left side assignment to evaluate tender instructions.
PHP defines some values that will be interpreted as false
, what is not listed 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 - tender comparison
Manual - precedence of operators
Soen - Understanding nested PHP Ternary Operator
Soen - PHP Ternary Operator not Working as expected
By your code
$var
is not an array.– rray
and it’s not even. but $var can be an array, and if it’s not I just hope it’s added, if it is, that an implode is made. Isn’t that the purpose of my expression? @rray
– Ale
I think the problem there is how to use the ternary in
echo
. If you do so:$var = 123;

$var2 = is_array($var) ? implode("-", $var) : $var;

echo $var2;
works....– gustavox
It seems that the string
'valor de var
makes the expression astrue
, test this:echo "valor de var: ". false ? implode("-", $var) : $var;
has another thing php uses left assign in ternario, that sinigica :P some unexpected results in some cases. Isolate yourself with parentheses works, as you expectecho "valor de var: ". (is_array($var) ? implode("-", $var) : $var);
– rray
I just isolated the ternary expression, it became something like:
(is_array($var) ? implode("-",$var) : $var)
and worked as expected, I think I understood what you said! very good.. @rray, grateful.– Ale
@Alexandrec.Caus, has one more example, I will try to answer.
– rray