I was accidentally creating a PHP script and, unintentionally, put an incremental operator on a variable whose type is array
.
To my surprise, no error was shown by PHP.
I made some tests and found that this really does not generate error for variables of type array
.
Test:
$dados['nome'] = 'wallace';
$empty = array();
$dados++;
$empty--;
print_r($dados);
print_r($empty);
Result:
Array
(
[nome] => wallace
)
Array
(
)
Before anyone comments or questions such things as "Why did you expect this to be a mistake?", I'll explain.
I know that increment and decrement operators work for values of type int
(with the exception of incrementing in PHP, which increments letters: p).
Then, for sum of values int
with array
, the expression below would return Fatal Error
:
$dados = array();
$dados + 1
Error generated:
Fatal error: Unsupported operand types
The sum operator in arrays
operates so that the values of array
on the left are entered in array
on the right, if they do not exist:
['nome' => 'wallace'] + ['idade' => 23, 'nome' => 'Wayne']
Result:
['nome' => 'wallace', 'idade' => 23]
So, I have some questions:
-
Why does not PHP generate any warning or error when I use array incrementing or decrementing operators?
-
Could this be considered a bug?
-
Is there any utility in using the increment operator in
array
that I have not noticed?