1

Today i very much wondered, that if the string contain first letter has integer you can add that value into another integer variable.

$a = 20;
$b = "5doller"; 
$a+=$b;
echo $a;

Will any one can explain how this is happen and if i have like string like "dollar5" it wont add.

2 Answers 2

3

PHP is not strongly typed.
since the first character of your string is an integer and you are using the + operator it interprets the 5dollar as int and returns 25
example: http://en.wikipedia.org/wiki/Strong_typing#Example

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

Comments

0

PHP has a type conversion philosofy, that will auto convert the type of the data on runtime depending on the context. This may have it's advantages and disadvantages, and there are people against it and people who think it's ok (like in almost everything in life).

For more info about its behaviour please have a look on the php documentation: http://www.php.net/manual/en/language.types.type-juggling.php

It will try to see the string as an integer to ease your life if you use the arithmetic operator "+"(detecting the first character "5"), but leading to strange behaviours if not done properly.

That doesn't mean it doesn't have a type, $b is actually a string, only that it tries to convert it on runtime, but $b will still remain as a string.

To check this and/or prevent the strange behaviours you could use the php native functions to check the types:

$a = 20;
$b = "5doller";
if(is_integer($b)){
    $a+=$b;
} elseif (is_string($b)) {
    $a.=$b;
}
echo $a;

Or you can use gettype() which will return the variable type, and do a switch case or whatever you like to it. But in my opinion it would be over-coding, just use your common sense and be careful and normally it will be ok.

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.