2

i wonder how the operation of addition works in case of one value to be numeric and other to be string For Example:

echo $j = 1 + "stackoverflow";

I tried executing this expression, It outputs me 1.. Can someone explain me why the string is not involved in addition, if it is involved then why is it converted to 0?

4 Answers 4

3

stackoverflow starts with no digit so php takes it 0

1stackoverflow would be 1 because it starts with digit 1

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

Comments

2

If you do this PHP tries to parse the integer value of the string. In this case "stackoverflow" is parsed to 0.

You can see for yourself what the integer value of a string is by using intval().

intval("stackoverflow"); // = 0
intval("123stackoverflow"); // = 123

Play around with it to get used to it.

Comments

1

In the operation above, PHP will try to convert both operands to numbers. Therefore "stackoverflow" string is actually converted to number - 0 in this case. Why this happens is best described in this manual page - converting string to numbers. Note that

$j = 1 + "1stackoverflow"

will produce 2 as the result.

Comments

0

Because it tries to convert the string to integer, and then adds it tot the number. It's basically the same as echo $j = 1 + intval("stackoverflow"); If you want to concatenate the string to the number, you have to use the concatenation operator, that is the dot: echo $j . "stackoverflow"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.