The expression
"a".(strlen('ab')-strlen('a'))
evaluates to a1 as expected.
But if I accidentally omit parentheses,
"a".strlen('ab')-strlen('a')
evaluates to -1. What is happening here?
The expression
"a".(strlen('ab')-strlen('a'))
evaluates to a1 as expected.
But if I accidentally omit parentheses,
"a".strlen('ab')-strlen('a')
evaluates to -1. What is happening here?
"a".strlen('ab')-strlen('a') is processed from left to right like:
"a".strlen('ab') becomes string "a2"
Now you have 'a2' - 1
You cannot substract from a string, so string 'a2' is casted to int thus becoming 0
0 - 1 which is -1.Related articles: operators precedence, string conversions.
I guess you might also get a Warning for non-numeric value when you omit the "()".
As a normal mathematical rule, the brackets are solved first so in the
"a".(strlen('ab')-strlen('a'))
strlen('ab') is 2 and,
strlen('a') is 1,
so 2-1= 1 and it gets concated with 'a' so becomes 'a1'.
And when you remove the parentheses,
"a".strlen('ab')-strlen('a')
then it executes left to right so
strlen('ab') concate's with 'a' which gives a2strlen('a') which is 1. so warning is displayed.The
"a".(strlen('ab')-strlen('a'))
operation first calculates the difference of the length of strings and then adds the result to "a", converting 1 into "1" in the process.
The
"a".strlen('ab')-strlen('a')
operation adds the length of 'ab' (2) to "a", resulting "a2". After that, from this String, the length of "a" (1) is subtracted, but since subtraction can only happen between numbers in PHP, therefore "a2" converted into 0 and subtracting 1 from here yields -1.