Ternary Operator, is_array, unexpected

5

See only .. Follow the instruction

$var = 123;

echo "valor de var: " . is_array($var) ? implode("-",$var) : $var;

Ai gives the following error: implode(): Invalid arguments passed .

I expected that the implode function would not be executed, since $var is not array, why is this?

Would it be some specific behavior of this ternary operator?

    
asked by anonymous 10.09.2015 / 04:56

2 answers

5

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

    
10.09.2015 / 05:51
4

Just delimit the ternary operation with parentheses.

Example:

$var = 123;

echo 'valor de var: '.(is_array($var)? implode('-',$var) : $var);
    
10.09.2015 / 06:00