0

May I write:

"1" + 1; 

In PHP, to get 2, or do I have to cast first:

(int)"1" + 1; 

? The reason I wonder this is because I have a counter in a text file that I want to increment:

file_put_contents($filename, file_get_contents($filename) + 1); 
3
  • @JohnConde Yes, it works, as I said to get 2 Commented Dec 24, 2015 at 21:36
  • 1
    I would avoid to relay on auto conversions, an explicit int cast is better IMHO. Commented Dec 24, 2015 at 21:36
  • if this "1" + 1; works, then it will work for your last statement as well Commented Dec 24, 2015 at 21:42

1 Answer 1

1

Yes, PHP cast string or char to integer itself, if the string is convertible to integer i.e,

"86"+6=92 and "91"+"9"=100 and "91a"+"8"=99 

But for "a"+6=6 and "a5"+5=5 and "a"+"a"=0

php can't cast "a5" to integer, so it cast it as 0 in integer same for "a"

Php is very loose scripting language

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

Comments