PHP में array से specific key के आधार पर element remove करने के तरीके।
विधि 1: unset() - Basic Removal
<?php $arr = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4]; unset($arr['b']); // Key 'b' remove करें print_r($arr); // Array ( [a] => 1 [c] => 3 [d] => 4 ) // Keys preserved: a, c, d (no re-index for associative)
विधि 2: array_diff_key() - Multiple Keys Remove
<?php $arr = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5]; $keysToRemove = ['b', 'd']; // Flip keys to use as filter $filter = array_flip($keysToRemove); // ['b' => 0, 'd' => 0] $result = array_diff_key($arr, $filter); print_r($result); // Array ( [a] => 1 [c] => 3 [e] => 5 )
विधि 3: array_filter() - Condition-based Removal
<?php
$arr = ['apple' => 1, 'banana' => 2, 'cherry' => 3, 'date' => 4];
// Keys starting with 'a' या 'c' remove करें
$filtered = array_filter($arr, function($value, $key) {
return !in_array($key[0], ['a', 'c']); // Keep if not a or c
}, ARRAY_FILTER_USE_BOTH);
print_r($filtered);
// Array ( [banana] => 2 [date] => 4 )
विधि 4: Numeric Arrays - Re-indexing के साथ
<?php $arr = ['John', 'Jacob', 'Tom', 'Tim']; // Keys: 0, 1, 2, 3 // Index 1 remove करें और re-index unset($arr[1]); $arr = array_values($arr); // Re-index to 0, 1, 2 print_r($arr); // Array ( [0] => John [1] => Tom [2] => Tim ) // One-liner with array_splice (better for numeric) $arr = ['John', 'Jacob', 'Tom', 'Tim']; array_splice($arr, 1, 1); // Removes AND re-indexes print_r($arr);
विधि 5: Reference द्वारा Remove (Loop में)
<?php
$arr = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4];
// Foreach by reference - modify original
foreach ($arr as $key => &$value) {
if ($key === 'b' || $key === 'd') {
unset($arr[$key]); // Safe: modifying array being iterated by reference
}
}
unset($value); // Break reference
print_r($arr); // [a => 1, c => 3]
Comparison Table
| Method | Use Case | Re-indexes | Multiple Keys |
|---|---|---|---|
unset($arr[$key]) | Single key known | नहीं | नहीं (loop में) |
array_diff_key() | Multiple known keys | नहीं | हाँ |
array_filter() | Condition-based | नहीं | हाँ |
array_splice() | Numeric index, sequential | हाँ | हाँ (range) |
unset + array_values() | Any, then re-index | हाँ | Loop में |
सावधानियां
- Foreach by value पर unset न करें - undefined behavior
- Reference loop के बाद
unset($value)करें - Associative arrays के लिए re-index न करें जब तक जरूरी न हो
- Null check:
unset($arr[$key] ?? null)safe है