What is the correct way to perform concatenation in PHP?

I understand that there is a difference between single quotes and double quotes. And after reading other stackOverfow questions and looking at this article, it seems like most people agree that the performance gain for using single quotes is negligible.

As a new PHP user, always using double quotes seems the most logical and least confusing. But why do people still share their double quoted links?

<?php $a = '12345'; echo "Numbers: $a !"; //What I think is good echo "Numbers: " . $a . " !"; //What my teacher,book and tutorials use. echo 'Numbers: ' . $a . ' !'; // Trick that gave a noticeable performance gain pre-PHP 4.3 ?> 

Why would we prefer the second or third method in the latest version of PHP today?

+4
source share
2 answers

Well, let's say you have $a = "apple"; , and you wanted to put it on the line "I love ______s!"

Using interpolation, your "preferred" method, you can try the following: "I love $as!" but of course it won’t work.

That's why I prefer to use "I love ".$a."s!" as this prevents any confusion. It also makes it easy to change it to access the array for any reason, so this is more of a "future update-proof." It should also be noted that most code editors cannot select an interpolated variable, so it is more difficult to find visually.

+3
source

I usually use the third method:

 echo 'Numbers: ' . $a . ' !'; 

I use single quotes as much as possible because I think it looks a lot cleaner. When I need things like a new line in my line, I usually write it separately from the rest of the line. This also points to this β€œspecial” line a little more:

 echo 'Numbers: ' . $a . ' !' . "\n"; 

I also think that the presence of variables inside double-quoted strings ( "like $so" ) is unclear, and you will not have syntax highlighting in many editors.

+3
source

Source: https://habr.com/ru/post/1484637/


All Articles