$a=1;
$b="abc";
echo $c=$a+$b;
Output :- 1
I am trying to understand how PHP works when string and int values are added.
$a=1;
$b="abc";
echo $c=$a+$b;
Output :- 1
I am trying to understand how PHP works when string and int values are added.
The example you have given will actually generate a warning that you may not see (depending upon your environment settings):
Warning: A non-numeric value encountered in [...][...] on line 3
However, PHP will do it's best to continue working and so execution does not stop.
What do you think PHP should do in the above case? It will attempt to convert $b to a numeric equivalent and carry on. In this case "abc" converts to 0 and is added to $a, giving the answer 1.
Consider the following instead:
$a=1;
$b="abc";
$d="2";
echo $c=$a+$b+$d;
What would you expect it to output? It outputs 3 because PHP can convert "2" to a numeric equivalent and adds it to the 1.
You can actually get PHP to tell you what the integer equivalent of a string is using intval or by an explicit cast to an int:
echo intval("abc");
echo (int)"abc";
As you should already expect by now, this outputs 0 in both cases.
When you are adding string and integer PHP evaluates as numeric type if string contains any leading numeric character it will only consider that numeric character. IF string does not contain numeric character then it will be evaluated as '0'.
so the answer to above is 1.
as 1+"abc" PHP will evaluate "abc" as zero. Hence
1+0 = 1