1

Today i am working on a small PHP code to plus/minus and multiply, but i end up found something which i wasn't knew before.

I was Plus 2 value, 123456+123456=24690 and my code is this:

<?php 
$value1=12345;
$value2=12345;

$output=$value1+$value2;

echo $output;
?>

Which return a correct value:

So than i have to print this value with string Like this:

Total Value: 24690

I use this code:

echo 'Total Value:'.$value1+$value2;

Its return: 12345 instead of

 Total Value: 24690

I know that "." isn't a Arithmetic operators, so i need small explanation why is this doing that.

But when i do

echo 'Total Value:'.($value1+$value2);

Its work fine!

Little Confused!

Muhammad
  • 103
  • 1
  • 12

3 Answers3

0

It first concatenates the $value1 with the string and then tries to add it to a string and number can't be added to string and hence you get that output.

While using braces, it just concatenates the contents of the brace and performs the mathematical operation inside the brace.

It follows BODMAS

Kinshuk Lahiri
  • 1,468
  • 10
  • 23
0

When you echo 'Total Value:'.$value1+$value2;

code execution will be like this actually:

echo ('Total Value: ' . $value1) + $value2;

Dharma Saputra
  • 1,524
  • 12
  • 17
-1

This behavior is called Type Juggling. From the manual it states:

a variable's type is determined by the context in which the variable is used. That is to say, if a string value is assigned to variable $var, $var becomes a string. If an integer value is then assigned to $var, it becomes an integer.

Example:

$foo = "1";  // $foo is string (ASCII 49)
$foo *= 2;   // $foo is now an integer (2)

More examples on the link.

Rax Weber
  • 3,730
  • 19
  • 30