Home > Article > Backend Development > Discussion: The difference between commas and periods in PHP
Let’s discuss with you the difference between commas and periods in PHP programming. Friends in need may wish to refer to it.
In PHP, commas are faster than periods. What is the reason? This article will tell you one by one. Look at the code first: <?php echo 'abc'.'def'; //用点号连接字符串 echo 'abc','def'; //用逗号连接字符串 //by bbs.it-home.org ?> Learn the difference between commas and periods in php through examples. Code: echo '1+5=' . 1+5; Look at the above. The output result is 6... instead of 1+5=6. Is it a bit magical? A magical example: echo "1+5=" . 5+1; //Output 2 Replace 5 and 1. The result becomes 2. Why is this? Is there no commutative property in addition in PHP? Of course not... Let's not think about why first. If I replace the period above with a comma, try it. echo '1+5=' , 5+1; //output 1+5=6 echo '1+5=' , 1+5; //Output 1+5=6 It can be seen that only using commas can get the expected results. So why doesn’t a period work? Why does a comma work? echo ('1+5' . 5)+1; //Output 2 After adding parentheses to the previous one, the result is the same. It proves that PHP first concatenates strings and then performs addition calculations from left to right. Since the string is connected first, it should be "1+55". Then use this string to add 1. Then why is 2 output? This is related to the mechanism of converting strings into numbers in PHP. Look at the example below: echo (int)'abc1'; //输出0 echo (int)'1abc'; //输出1 echo (int)'2abc'; //输出2 echo (int)'22abc'; //输出22 As can be seen from the above example: If you force a string to be converted to a number, PHP will search for the beginning of the string. If the beginning is a number, it will be converted. If not, it will directly return 0. Go back to 1+55 just now. Since this string is 1+55, it should be 1 after forced type conversion. Add 1 to this, and of course it will be 2. Verify it: echo '5+1=' . 1+5; //输出10 echo '5+1=' . 5+1; //输出6 echo '1+5=' . 1+5; //输出6 echo '1+5=' . 5+1; //输出2 Proven correct. So why does using commas eliminate the above problems? The manual says that using commas means multiple parameters. That is to say, it is multi-parameter, that is, the ones separated by commas are equivalent to N parameters. In other words, echo is used as a function. In this way, echo will first calculate each parameter, and finally connect it and output it, so using commas does not cause the above problem. |