5

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.

13
  • unset($array[0]); you have unset the 0 index. Commented Dec 8, 2017 at 13:27
  • This has been answered before: stackoverflow.com/questions/5217721/… Commented Dec 8, 2017 at 13:28
  • @DragonZero I use array_values... But if the array is empty, it not work... If I've an array with 3 values, I remove the 2nd and do a array_values, keyes are redistributed correctly, but if array is empty, it do nothing... Commented Dec 8, 2017 at 13:30
  • 3
    Clearly a behavioural difference between versions: 3v4l.org/auHLM. Might want to consider filing a bug report. Commented Dec 8, 2017 at 13:35
  • 1
    @KresimirPendic array_values bug, it doesn't work when the array is empty Commented Dec 8, 2017 at 13:48

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.