Ryan
Ryan

Reputation: 6057

Should I use . or , to separate variables in PHP short tag echo?

For example:

<?php 

$var1 = 'cow';
$var2 = 'lamb';

?>

<?=$var1,$var2?>

or should that last part be:

<?=$var1.$var2?>

Upvotes: 2

Views: 512

Answers (1)

Luc
Luc

Reputation: 6026

The operation you're performing is concatenation. Technically you can also use a comma as well, but for clarity I would use the concatenation operator, which is a period (or dot).

Using a comma seems to be slightly faster, but this kind of speed differences are negligible. Code should always be optimized for reading (it's hard to read by definition already), only when serious performance issues are encountered you can start optimization. And even then, replacing concatenation with passing multiple arguments is not going to improve much.

Also, this works only for the echo() function. Consistency is usually good thing.

P.S. Using a space after a comma or around operators is also often recommended for readability:

<?=$var1 . $var2?>
<?=$var1, $var2?>

Upvotes: 3

Related Questions