0
$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.

2
  • If it's a numeric string, it converts it to number for addition, else, it throws a warning. See here 3v4l.org/n0Bmd . But this isn't a very well defined behavior in PHP, so the bottom line is never do such operations if you aren't sure about the datatype. Commented Sep 23, 2019 at 11:14
  • why won't you check yourself:- 3v4l.org/GhTv9 Commented Sep 23, 2019 at 11:14

2 Answers 2

1

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.

Source ref: intval and (int)

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.