Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete key from array and update index?

Tags:

arrays

php

$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'
}
like image 345
lisovaccaro Avatar asked Jul 22 '12 23:07

lisovaccaro


People also ask

How do you remove an element from an array and a shift index?

To remove an array element at index i, you shift elements with index greater than i left (or down) by one element. For example, if you want to remove element 3, you copy element 4 to element 3, element 5 to element 4, element 6 to element 5.

How do you delete a key from an array?

Using unset() Function: The unset() function is used to remove element from the array. The unset function is used to destroy any other variable and same way use to delete any element of an array. This unset command takes the array key as input and removed that element from the array.

How do I remove an item from an array index?

Find the index of the array element you want to remove using indexOf , and then remove that index with splice . The splice() method changes the contents of an array by removing existing elements and/or adding new elements. The second parameter of splice is the number of elements to remove.

How do I change the value of a key in an array?

Change Array Key using JSON encode/decode It's short but be careful while using it. Use only to change key when you're sure that your array doesn't contain value exactly same as old key plus a colon. Otherwise, the value or object value will also get replaced.


2 Answers

Check this:

$array = array('a', 'b','c');
unset($array[0]);
$array = array_values($array); //reindexing
like image 191
Zhafur Avatar answered Oct 31 '22 10:10

Zhafur


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.

like image 13
VoteyDisciple Avatar answered Oct 31 '22 11:10

VoteyDisciple