Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding string with number in php

Tags:

php

$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

like image 978
rynhe Avatar asked Jun 14 '12 04:06

rynhe


People also ask

Can we add string and number in PHP?

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.

What is the result of combining a string with a number in PHP?

A string and an integer value are added, and the result is an integer value. Concatenation operator ('. ')

How do I add characters to a string in PHP?

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.

What is a numeric string PHP?

Numeric strings ¶ A PHP string is considered numeric if it can be interpreted as an int or a float.


2 Answers

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.

like image 111
xbonez Avatar answered Nov 15 '22 14:11

xbonez


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

like image 33
fyquah95 Avatar answered Nov 15 '22 13:11

fyquah95