$a = "3dollars";
$b = 20;
echo $a += $b;
print($a += $b);
Result:
23 43
I have a question from this calculation.$a is a string and $b is number.I am adding both and print using echo its print 23 and print using print return 43.How is it
PHP automatically associates a data type to the variable, depending on its value. Since the data types are not set in a strict sense, you can do things like adding a string to an integer without causing an error.
A string and an integer value are added, and the result is an integer value. Concatenation operator ('. ')
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.
Numeric strings ¶ A PHP string is considered numeric if it can be interpreted as an int or a float.
It casts '3dollars' as a number, getting $a = 3
.
When you echo, you add 20, to $a
, so it prints 23
and $a = 23
.
Then, when you print, you again add 20, so now $a = 43
.
The right way to add (which is technically concatenating) strings is
$a = 7;
$b = "3 dollars";
print ($a . $b); // 73 dollars
The +
operator in php automatically converts string into numbers, which explains why your code carried out arimethic instead of concatenation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With