PHP में array से element remove करने और keys को re-index करने के तरीके।
समस्या: unset() Keys Re-index नहीं करता
<?php
$arr = ['John', 'Jacob', 'Tom', 'Tim'];
unset($arr[1]); // 'Jacob' remove
print_r($arr);
/*
Array
(
[0] => John
[2] => Tom // Key 2! Gap रह गया
[3] => Tim
)
*/
समाधान 1: array_values() - Re-index करें
<?php
$arr = ['John', 'Jacob', 'Tom', 'Tim'];
unset($arr[1]);
$arr = array_values($arr); // Re-index to 0, 1, 2...
print_r($arr);
/*
Array
(
[0] => John
[1] => Tom
[2] => Tim
)
*/
समाधान 2: array_splice() - Remove + Re-index एक साथ
<?php $arr = ['John', 'Jacob', 'Tom', 'Tim']; // Remove 1 element at index 1 array_splice($arr, 1, 1); print_r($arr); // [0 => John, 1 => Tom, 2 => Tim] // Multiple remove $arr = ['a', 'b', 'c', 'd', 'e']; array_splice($arr, 1, 2); // Index 1 से 2 elements remove print_r($arr); // [0 => a, 1 => d, 2 => e]
समाधान 3: Value द्वारा Remove (Key पता नहीं)
<?php
$arr = ['John', 'Jacob', 'Tom', 'Tim'];
$valueToRemove = 'Jacob';
$key = array_search($valueToRemove, $arr);
if ($key !== false) {
unset($arr[$key]);
$arr = array_values($arr);
}
print_r($arr);
// सभी occurrences remove करें
$arr = ['a', 'b', 'a', 'c', 'a'];
$arr = array_values(array_diff($arr, ['a'])); // ['b', 'c']
समाधान 4: Associative Arrays के लिए
<?php $assoc = ['name' => 'John', 'age' => 25, 'city' => 'NYC']; // Specific key remove unset($assoc['age']); // Keys preserved (associative के लिए re-index नहीं चाहिए usually) // यदि numeric re-index चाहिए $reindexed = array_values($assoc); // [0 => 'John', 1 => 'NYC']
Filtering Approaches (Cleaner)
<?php
$arr = ['John', 'Jacob', 'Tom', 'Tim'];
// Condition-based removal + re-index
$filtered = array_values(array_filter($arr, function($name) {
return $name !== 'Jacob'; // Keep all except Jacob
}));
// या arrow function (PHP 7.4+)
$filtered = array_values(array_filter($arr, fn($n) => $n !== 'Jacob'));
Performance Comparison (10000 elements, remove 1)
| Method | Time | Notes |
|---|---|---|
unset + array_values | ~0.15ms | Two passes |
array_splice | ~0.12ms | Single pass, best for index-based |
array_filter + array_values | ~0.18ms | Value-based, clean syntax |
array_diff + array_values | ~0.20ms | Multiple values remove |
सिफारिश
- Index known:
array_splice($arr, $index, 1) - Value known:
array_values(array_filter(...)) - Multiple values:
array_values(array_diff($arr, $toRemove)) - Associative arrays:
unset($arr[$key])(re-index न करें)