Take 5 different languages:

Ruby

Python

Javascript

C ++

Java

All of them are united by the fact that there is a '+' operator for string concatenation. This operator is logical - we want to add two lines - we add. I spent an hour trying to understand why the echo "str" + " yolo" code echo "str" + " yolo" returns 0 , but not what I want and my torments were resolved only with a startling discovery that concatenation is the '.' How do the creators of the language explain such a trick? What are the reasons for replacing an established operator?

  • 2
    I think it makes no sense to focus on this. You just need to remember this ..... For so you can ask about any YP. Why do you write cout << 2002; or why in this or that language elif instead of elseif , etc. - Alexey Shimansky

2 answers 2

Everything is very simple. Once upon a time php was written in pearl. Roughly speaking, php was just a perl template engine. And therefore, there are many “features” that came from. In Perl adopted at first glance a strange, but quite logical system. Operands do not define an operation, but an operation. That is, '+' adds numbers. And if the variables are not numbers, then they will be converted to them. Similar, '.' - this is a concatenation of strings (if to be a pedant, then strings cannot be added). And operation '.' converts the operands to strings as needed and concatenates.

PS Now in php dragged the operator "flying saucer" - <=> , which in perl was for years :)

  • For those who did not know about the "flying saucer": tyts ; but in the Russian version of the documentation ( clack ) has not yet written ... - Roman Grinyov

Because in php you can do operations on strings as with numbers. This means that the operations of addition of numbers and concatenation must be somehow distinguished. True, I think so :) For example:

 $first = "9"; $second = "1"; $a . $b; // 91 $a + $b; // 10 

In your case echo "str" + " yolo" -> both texts were reduced to a number - in this case to zero. Well, the result you received is appropriate.