Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to delete an element from an array in PHP and re-index the array?
In PHP, you can delete an element from an array using the unset() function. However, this creates gaps in the array indices. To re−index the array with consecutive numeric keys, use the array_values() function.
Using unset() and array_values()
The unset() function removes an element by its key, while array_values() returns a new array with consecutive numeric indices ?
<?php
$my_arr = array('this', 'is', 'a', 'sample', 'only');
echo "Original array:
";
var_dump($my_arr);
// Remove element at index 2
unset($my_arr[2]);
echo "\nAfter unset (with gaps):
";
var_dump($my_arr);
// Re-index the array
$my_arr_reindexed = array_values($my_arr);
echo "\nAfter re-indexing:
";
var_dump($my_arr_reindexed);
?>
Original array:
array(5) {
[0]=>
string(4) "this"
[1]=>
string(2) "is"
[2]=>
string(1) "a"
[3]=>
string(6) "sample"
[4]=>
string(4) "only"
}
After unset (with gaps):
array(4) {
[0]=>
string(4) "this"
[1]=>
string(2) "is"
[3]=>
string(6) "sample"
[4]=>
string(4) "only"
}
After re-indexing:
array(4) {
[0]=>
string(4) "this"
[1]=>
string(2) "is"
[2]=>
string(6) "sample"
[3]=>
string(4) "only"
}
Alternative: Using array_splice()
You can also use array_splice() to remove elements and automatically re−index in one step ?
<?php
$fruits = array('apple', 'banana', 'cherry', 'date', 'elderberry');
echo "Original array:
";
print_r($fruits);
// Remove element at index 1 (banana)
array_splice($fruits, 1, 1);
echo "\nAfter array_splice:
";
print_r($fruits);
?>
Original array:
Array
(
[0] => apple
[1] => banana
[2] => cherry
[3] => date
[4] => elderberry
)
After array_splice:
Array
(
[0] => apple
[1] => cherry
[2] => date
[3] => elderberry
)
Conclusion
Use unset() followed by array_values() for simple element removal with re−indexing, or array_splice() for a one−step solution that automatically maintains consecutive indices.
Advertisements
