What do the incrementing operators do in arrays?

3

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?

asked by anonymous 14.12.2015 / 14:35

2 answers

4
  

The increment / decrement operators affect only numbers and strings. Arrays, objects, and features are not affected. Decreasing NULL does not generate effects, but incrementing results in 1.

link

    
14.12.2015 / 15:34
2

An error occurs when using the in / decrement operator on an array or object because nothing is affected by documentation says:

  

Note: The increment / decrement operators only affect numbers and strings. Arrays, objects, and resources are not affected.

    
14.12.2015 / 15:37