Is this behaviour correct in PHP?
<?php echo '-' . 1 + 1 . ' crazy cats'; ?>
// Outputs:
0 crazy cats
I understand that minus is being concatenated to the first '1' and '-1' casted to integer, and not '2' to string.
Please explain why.
What is the best way to solve it? This one?
<?php echo '-' . (string)1 + 1 . ' crazy cats'; ?>
Precedence of operators decides the order of execution of operators in an expression. For example in 2+6/3, division of 6/3 is done first and then addition of 2+2 takesplace because division operator / has higher precedence over addition operator +.
The logical-AND operator ( && ) has higher precedence than the logical-OR operator ( || ), so q && r is grouped as an operand. Since the logical operators guarantee evaluation of operands from left to right, q && r is evaluated before s-- .
The precedence of an operator specifies how "tightly" it binds two expressions together. For example, in the expression 1 + 5 * 3 , the answer is 16 and not 18 because the multiplication ("*") operator has a higher precedence than the addition ("+") operator. Parentheses may be used to force precedence, if necessary.
The best way to force your own operator precedence is to place parentheses around subexpressions to which you wish to give high precedence. Operator associativity refers to the direction of processing (left-to-right or right-to-left).
First of all, it is correct, and if it would be different it would also be correct, that's how PHP developers defined operand precedence.
In this scenario, no operand has precedence, so u read it left to right
'-' . 1 ==> '-1'
'-1' + 1 ==> 0
(arithmetic operations on strings, will try to cast them to numbers first and then do the arithmetics).0 . ' crazy cats' ==> "0 crazy cats"
(strings operations on numbers, will cast them to strings).If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With