PHP type privilege exceeded

Is this behavior correct in PHP?

<?php echo '-' . 1 + 1 . ' crazy cats'; ?> // Outputs: 0 crazy cats 

I understand that minus is combined in the first "1" and "-1", cast as an integer, rather than "2" in a string.

Please explain why.

What is the best way to solve it? This?

 <?php echo '-' . (string)1 + 1 . ' crazy cats'; ?> 
+6
source share
5 answers

If you prefer, this avoids priority:

 printf('-%d crazy cats',1+1); 
+1
source

First of all, this is correct, and if it were otherwise, it would also be correct for PHP developers to prioritize the operand.
In this case, none of the operands has priority, so you read it from left to right

  • '-' . 1 ==> '-1'
  • '-1' + 1 ==> 0 (arithmetic operations on strings, try to first transfer them to numbers, and then do arithmetic).
  • 0 . ' crazy cats' ==> "0 crazy cats" 0 . ' crazy cats' ==> "0 crazy cats" (operations with lines by numbers, drop them into lines).
+6
source

If you want 2 crazy cats, you can set the control priority in brackets:

 echo '-' . (1 + 1) . ' crazy cats'; 
+4
source

echo also follows the echo 'foo', 'bar' construct, which splits elements into separate expressions into echoes. In this case, you do not need to worry about the concatenation order.

So, you could do <?php echo '-', (1 + 1), ' crazy cats'; ?> <?php echo '-', (1 + 1), ' crazy cats'; ?> and your cats would not care about the negatives!

+3
source

Your phrase is disabled. '-' not executed, but is specified.

PHP will still process (string) 1 and -1 as an integer.

. and +/- have the same priority in PHP, so the string can be read from left to right.

The above is an example:

 echo '-1' + '1 crazy cats'; 
+1
source

Source: https://habr.com/ru/post/920850/


All Articles