karim_fci
karim_fci

Reputation: 1242

PHP String Concatenation (one from variable and another from ternary opeartor) give unexpected results

I am describing the problem by example: let,

$actual_food['Food']['name'] = 'Tea';
$actual_food['Food']['s_name'] = 'Local';

I am concatenating the aforesaid variables in following way.

$food_name = $actual_food['Food']['name']." ".!empty($actual_food['Food']['s_name']) ? "- ".$actual_food['Food']['s_name'] : "";

when i print $food_name then the output like ' - Local' but does not print $actual_food['Food']['name'] content.

I think this question is very little bit silly but my curious mind wants to know. Thanks in advance.

Upvotes: 4

Views: 78

Answers (2)

Narendrasingh Sisodia
Narendrasingh Sisodia

Reputation: 21437

You need to take care about concatenation while using ternary operators. You can try as

$food_name = ($actual_food['Food']['name'])." ".(!empty($actual_food['Food']['s_name']) ? "- ".$actual_food['Food']['s_name'] : "");
echo $food_name;// Tea - Local

Over here I've enclosed the variables within parenthesis ()

Its because of what we call operator precedence. If we don't enclose the ternary operator within parenthesis then your code will be interpreted like as

($actual_food['Food']['name'] . " " . !empty($actual_food['Food']['s_name']) ?...;

So you simply enclose your ternary operator for correct interpretation

Upvotes: 3

Hassaan
Hassaan

Reputation: 7672

Try

$actual_food['Food']['name'] = 'Tea';
$actual_food['Food']['s_name'] = 'Local';

$food_name = !empty($actual_food['Food']['s_name']) ? $actual_food['Food']['name']." - ".$actual_food['Food']['s_name'] : $actual_food['Food']['name'];

echo $food_name;

OR

Add () before and after !empty condition like

 $food_name = $actual_food['Food']['name']." ".(!empty($actual_food['Food']['s_name']) ? "- ".$actual_food['Food']['s_name'] : "");

Upvotes: 0

Related Questions