Removing Array Element and Re-Indexing in PHP
In order to remove an element from an array, we can use unset() function which removes the element from an array, and then use array_values() function which indexes the array numerically automatically.
Function Used
unset():
This function unsets a given variable.
Syntax:void unset ( mixed $var [, mixed $... ] )
array_values():
This function returns all the values from the array and indexes the array numerically.
Syntax:array array_values ( array $array )
Example 1: We can also use array_splice() function which removes a portion of the array and replaces it with something else.
<?php
$arr1 = array(
'geeks', // [0]
'for', // [1]
'geeks' // [2]
);
// remove item at index 1 which is 'for'
unset($arr1[1]);
// Print modified array
var_dump($arr1);
// Re-index the array elements
$arr2 = array_values($arr1);
// Print re-indexed array
var_dump($arr2);
?>
Output
array(2) { [0]=> string(5) "geeks" [2]=> string(5) "geeks" } array(2) { [0]=> string(5) "geeks" [1]=> string(5) "geeks" }
Example 2:
<?php
$arr1 = array(
'geeks', // [0]
'for', // [1]
'geeks' // [2]
);
// remove item at index 1 which is 'for'
array_splice($arr1, 1, 1);
// Print modified array
var_dump($arr1);
?>
Output
array(2) { [0]=> string(5) "geeks" [1]=> string(5) "geeks" }
Using array_filter() with a Callback Function
Using `array_filter()` with a callback function allows you to remove specific elements from an array by filtering out elements based on a condition. The `ARRAY_FILTER_USE_KEY` flag enables filtering by key. The resulting array is then re-indexed with `array_values()`.
Example:
<?php
$array = ['apple', 'banana', 'cherry'];
$indexToRemove = 1; // Remove 'banana'
// Filter out the element at the specified index
$array = array_filter($array, function($key) use ($indexToRemove) {
return $key != $indexToRemove;
}, ARRAY_FILTER_USE_KEY);
// Re-index the array
$array = array_values($array);
print_r($array);
?>
Output
Array ( [0] => apple [1] => cherry )
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.