Home » Php » php – How to delete key from array and update index?

php – How to delete key from array and update index?

Posted by: admin July 12, 2020 Leave a comment

Questions:
$array = array('a', 'b','c');
unset($array[0]);
var_dump($array);

Yields:
array(1) {
  [1]=>
  'b'
  'c'
}

How do I, remove array[0] to get [‘bb’,’cc’] (no empty keys):

array(1) {
  'b'
  'c'
}
How to&Answers:

Check this:

$array = array('a', 'b','c');
unset($array[0]);
$array = array_values($array); //reindexing

Answer:

Take a look at array_splice()

$array = array_splice($array, 0, 1);

If you happen to be removing the first element specifically (and not an arbitrary element in the middle of the array), array_shift() is more appropriate.