$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'
}
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.
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.
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.
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.
Check this:
$array = array('a', 'b','c');
unset($array[0]);
$array = array_values($array); //reindexing
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With