Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP concatenation precedence

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'; ?>
like image 937
Paker Avatar asked Jul 19 '12 01:07

Paker


People also ask

Which operator has highest precedence in PHP?

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 +.

Which operator has the highest order of precedence?

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-- .

What is the correct operator precedence?

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.

What is the best way to force your own operator precedence?

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).


1 Answers

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'
  2. '-1' + 1 ==> 0 (arithmetic operations on strings, will try to cast them to numbers first and then do the arithmetics).
  3. 0 . ' crazy cats' ==> "0 crazy cats" (strings operations on numbers, will cast them to strings).
like image 163
Itay Moav -Malimovka Avatar answered Oct 13 '22 13:10

Itay Moav -Malimovka