Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Misunderstanding of array_values

Tags:

php

php-7

php-7.2

I've a problem to unerstand correctly array_values, when I do:

$array[] = 'data1'; // I want [0 => 'data1']
unset($array[0]); // I want []
$array = array_values($array); // I want [] but keys resetted
$array[] = 'data2'; // I want [0 => 'data2']
$array[] = 'data3'; // I want [0 => 'data2', 1 => 'data3']
dump($array);

I've the result:

array:2 [▼
  1 => "data2"
  2 => "data3"
]

But I'll want:

array:2 [▼
  0 => "data2"
  1 => "data3"
]

Maybe someone can explain it to me ? Because I'm a little lost :-/

For exemple, if I've an array with 10 values in, remove the 3rd value, and do an array_values on, it works well.

But if I remove the last value from an array, then when I do a array_value, the next value I add, always have id 1 and not 0.

like image 406
mpiot Avatar asked Nov 19 '22 02:11

mpiot


1 Answers

This behaviour has been already reported as a bug: https://bugs.php.net/bug.php?id=75433 and (apparently as the result of this post) also: https://bugs.php.net/bug.php?id=75653

like image 182
Jirka Hrazdil Avatar answered Dec 04 '22 08:12

Jirka Hrazdil