What do increment operators do in arrays?

Asked

Viewed 75 times

3

Accidentally I was creating a PHP script and unintentionally put an increment operator in a variable whose type is array.

To my surprise, no error was shown by PHP.

I did some tests and found that really this does not generate error for type variables array.

Testing:

$dados['nome'] = 'wallace';

$empty = array();

$dados++;

$empty--;

print_r($dados);

print_r($empty);

Upshot:

Array
(
    [nome] => wallace
)
Array
(
)

Before someone makes a comment or questions things like "And why did you expect it to return an error?" I explain to you.

That I know increment and decrease operators work for values like int (except for the increment in PHP, which increments letters :p).

So, in the case of sum of values int with array, the expression below would return a Fatal Error:

$dados = array();

$dados + 1

Error generated:

Fatal error: Unsupported operand types

The sum operator in arrays operate so that the values of the array are inserted into the array right, if there are no:

['nome' => 'wallace'] + ['idade' => 23, 'nome' => 'Wayne']

Upshot:

['nome' => 'wallace', 'idade' => 23]

So I have a few questions:

  • Why PHP does not generate any warning or error when using increment or decrement operators in arrays?

  • This could be considered a bug?

  • Is there any utility in using the increment operator in array that I haven’t noticed?

  • 1

    Yes, PHP is a bug :D

  • 1

    @bigown I’ll be honest with you: I know php has many mistakes, but I really like it. Your comment deserved a decrementation operator

  • Even the error occurs, but PHP cannot identify the error, if you try it: <?php ini_set("display_errors", "1");&#xA;error_reporting(-1);&#xA;echo $empty[]; ?> shows no error, but if show this: gives error: <?php ini_set("display_errors", "1");&#xA;error_reporting(-1);&#xA;echo $empty; ?> is like a bug itself.

2 answers

4


2

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

Note: The increment/decrement Operators only affect Numbers and strings. Arrays, Objects and Resources are not affected.

  • Then php having this in mind should throw an error. Jeep PHP, even so I love you

  • 2

    @Wallacemaxters, also think you should return a Unsupported operand types

Browser other questions tagged

You are not signed in. Login or sign up in order to post.