Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does addition "+" of two strings in PHP produce this result?

Tags:

string

php

In PHP, "aaa" + "bbb" would produce 0.

I know that to concatenate two strings in PHP, I need to use .. But I don't know why does addition + of two strings in PHP produce this result?

like image 341
Yuhang Lin Avatar asked Oct 25 '17 22:10

Yuhang Lin


People also ask

How to combine 2 strings in PHP?

The first is the concatenation operator ('. '), which returns the concatenation of its right and left arguments. The second is the concatenating assignment operator ('. ='), which appends the argument on the right side to the argument on the left side.

How to add string to string in PHP?

Answer: Use the PHP String Operators There is no specific function to append a string in PHP. But you can use the PHP concatenation assignment operator ( . = ) to append a string with another string.

How to concat variable in PHP?

The concatenate term in PHP refers to joining multiple strings into one string; it also joins variables as well as the arrays. In PHP, concatenation is done by using the concatenation operator (".") which is a dot.

How to combine string values in PHP?

PHP Compensation Operator is used to combine character strings. The PHP concatenation operator (.) is used to combine two string values to create one string. Concatenation assignment.

What is the use of concatenation in PHP?

Operator Description. The PHP concatenation operator (.) is used to combine two string values to create one string..= Concatenation assignment.

How to add string in PHP?

String adding in PHP. We can add two strings and generate a new string in PHP by using a single dot. This way we can add any number of strings by using " . " ( dot ) in between them. We will learn different types of string addition in PHP. Let us start with simple adding of two strings by using a single dot between them. Here is the example.

What are the string operators in PHP?

There are two string operators provided by PHP. 1.Concatenation Operator ("."): This operator combines two string values and returns it as a new string. 2.Concatenating Assignment operator (".="): This operation attaches the argument on the right side to the argument on the left side.


1 Answers

When you use arithmetic operators on non-numbers then PHP casts them to integer type. PHP is sort of smart, so string "1" would be cast to integer 1 and string "1.0" would be cast to float, however "aaa" would be cast to integer 0, as well as "bbb". So both cast to 0 is 0 + 0 which obviously is 0.

See PHP: String conversion to numbers.

As of PHP 7.1.0 this generates:

Warning: A non-numeric value encountered

However, this is fine since they are numeric though not a numeric type (strings):

var_dump("1" + "2");
like image 118
AbraCadaver Avatar answered Oct 21 '22 20:10

AbraCadaver