How the string is add to integer in PHP -
today wondered, if string contain first letter has integer can add value integer variable.
$a = 20; $b = "5doller"; $a+=$b; echo $a;
will 1 can explain how happen , if have string "dollar5" wont add.
php has type conversion philosofy, auto convert type of data on runtime depending on context. may have it's advantages , disadvantages, , there people against , people think it's ok (like in in life).
for more info behaviour please have on php documentation: http://www.php.net/manual/en/language.types.type-juggling.php
it try see string
integer
ease life if use arithmetic operator "+"(detecting first character "5"), leading strange behaviours if not done properly.
that doesn't mean doesn't have type, $b string
, tries convert on runtime, $b still remain string
.
to check and/or prevent strange behaviours use php native functions check types:
$a = 20; $b = "5doller"; if(is_integer($b)){ $a+=$b; } elseif (is_string($b)) { $a.=$b; } echo $a;
or can use gettype()
return variable type, , switch case or whatever it. in opinion over-coding, use common sense , careful , ok.
Comments
Post a Comment