PHP string concatenation (one of the variable and the other of the triple version) gives unexpected results

I describe the problem with an example: let

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

I concatenate the above variables as follows.

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

when I print $food_name , then output similar to '- Local' but does not print the $actual_food['Food']['name'] contents.

I think this question is very slightly stupid, but my curious mind wants to know. Thanks in advance.

+4
source share
2 answers

You need to take care of concatenation when using ternary operators. You can try how

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

Here I have enclosed the variables in parenthesis ()

Due to what we call operator precedence . If we do not enclose the ternary operator in parentheses, then your code will be interpreted as

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

So you just wrap your ternary operator for the correct interpretation

+3
source

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'] : ""); 
0
source

All Articles