3020

Is there an easy way to delete an element from an array using PHP, such that foreach ($array) no longer includes that element?

I thought that setting it to null would do it, but apparently it does not work.

Star
  • 3,222
  • 5
  • 32
  • 48
Ben
  • 66,838
  • 37
  • 84
  • 108
  • 17
    I would not that Konrad answer is the simplest one to the stated problem. With `unset()` the iterations over the array will not include the removed value anymore. OTOH, it is true that Stevan answer is ample and, actually, was the answer I was looking for - but not the OP :) – brandizzi Jul 26 '12 at 17:05
  • 48
    @danip Being easy to find in the manual does not preclude a question on StackOverflow. If the question were a *duplicate* StackOverflow question, then it might not belong here. StackOverflow is a good place to find answers as a go-to option even before looking in the manual. – Dan Nissenbaum Feb 11 '14 at 05:18
  • 7
    @unset($array[$key]); $array = array_values($array); – trojan Sep 04 '14 at 12:55
  • Related question about removing this in a foreach loop: http://stackoverflow.com/questions/1949259/how-do-you-remove-an-array-element-in-a-foreach-loop – Legolas Sep 23 '15 at 08:18
  • 2
    If you want to remove keys from array of array (Associative array), see solution at https://stackoverflow.com/a/47978980/1045444 – Somnath Muluk Dec 26 '17 at 13:10
  • 2
    you can do it in a foreach loop like this: https://www.pastefs.com/pid/130950 – Aurangzeb Jun 25 '19 at 10:50
  • 2
    Setting an array key value to null simple means includes a key that has a null value. The key still exists. – blakroku Nov 20 '19 at 07:05

25 Answers25

3541

There are different ways to delete an array element, where some are more useful for some specific tasks than others.

Deleting a Single Array Element

If you want to delete just one single array element you can use unset() and alternatively array_splice().

By key or by value?

If you know the value and don't know the key to delete the element you can use array_search() to get the key. This only works if the element doesn't occur more than once, since array_search() returns the first hit only.

unset() Expression

Note: When you use unset() the array keys won’t change. If you want to reindex the keys you can use array_values() after unset(), which will convert all keys to numerically enumerated keys starting from 0 (the array remains a list).

Example Code:

$array = [0 => "a", 1 => "b", 2 => "c"];
unset($array[1]);
          // ↑ Key of element to delete

Example Output:

[
    [0] => a
    [2] => c
]

array_splice() Function

If you use array_splice() the (integer) keys will automatically be reindex-ed, but the associative (string) keys won't change — as opposed to array_values() after unset(), which will convert all keys to numerical keys.

Note: array_splice() needs the offset, not the key, as the second parameter; offset = array_flip(array_keys(array))[key].

Example Code:

$array = [0 => "a", 1 => "b", 2 => "c"];
array_splice($array, 1, 1);
                  // ↑ Offset of element to delete

Example Output:

[
    [0] => a
    [1] => c
]

array_splice(), same as unset(), take the array by reference. You don’t assign the return values back to the array.

Deleting Multiple Array Elements

If you want to delete multiple array elements and don’t want to call unset() or array_splice() multiple times you can use the functions array_diff() or array_diff_key() depending on whether you know the values or the keys of the elements to remove from the array.

array_diff() Function

If you know the values of the array elements which you want to delete, then you can use array_diff(). As before with unset() it won’t change the keys of the array.

Example Code:

$array = [0 => "a", 1 => "b", 2 => "c", 3 => "c"];
$array = array_diff($array, ["a", "c"]);
                         // └────────┘
                         // Array values to delete

Example Output:

[
    [1] => b
]

array_diff_key() Function

If you know the keys of the elements which you want to delete, then you want to use array_diff_key(). You have to make sure you pass the keys as keys in the second parameter and not as values. Keys won’t reindex.

Example Code:

$array = [0 => "a", 1 => "b", 2 => "c"];
$array = array_diff_key($array, [0 => "xy", "2" => "xy"]);
                              // ↑           ↑
                              // Array keys of elements to delete

Example Output:

[
    [1] => b
]

If you want to use unset() or array_splice() to delete multiple elements with the same value you can use array_keys() to get all the keys for a specific value and then delete all elements.

array_filter() Function

If you want to delete all elements with a specific value in the array you can use array_filter().

Example Code:

$array = [0 => "a", 1 => "b", 2 => "c"];
$array = array_filter($array, static function ($element) {
    return $element !== "b";
    //                   ↑
    // Array value which you want to delete
});

Example Output:

[
    [0] => a
    [1] => c
]
hakre
  • 193,403
  • 52
  • 435
  • 836
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • if you have int(0), [1]=> int(2), [3]=> int(4), } ?> – Alexandru R Jun 13 '12 at 12:23
  • 31
    @AlexandruRada No, you said “don’t use this” – and that’s just nonsense. You can safely use this method when you treat an array as what it is – a dictionary. Only if you are expecting consecutive numeric indices do you need to use something else. – Konrad Rudolph Jun 13 '12 at 12:26
  • 1
    @AlexandruRada There is no way you can have `array (3) { [0]=>int(0) ...` when you `unset($x[2])` from `$x = array(1, 2, 3, 4);` Result **must** be `var_dump($x); // array(3) { [0]=> int(1) [1]=> int(2) [3]=> int(4) }` (it was probably typo) – inemanja Apr 19 '16 at 05:33
  • 9
    `unset` can have multiple arguments: `void unset ( mixed $var [, mixed $... ] )`. – Константин Ван Apr 14 '17 at 03:12
  • 4
    array_filter is also a viable method. Especially good if you don't want to mutate the array but it also doesn't reindex which can be an issue with json_encode. http://php.net/manual/en/function.json-encode.php#94157 – dotnetCarpenter May 06 '17 at 00:20
  • In `array_splice` and another codes, must know key or values name of array, and so some time reindex key array, for remove first item with keep order of index and if don't know index item, can use this method: https://stackoverflow.com/a/52826684/1407491 – Nabi K.A.Z. Oct 16 '18 at 01:23
  • Is there is any way to delete array element from multi dimensional (key, value) array . – Kuldeep singh Jul 11 '19 at 06:27
  • For delete multiple elements or check in multi dimensional arrays, array_map can be an useful addition. – Moisés Márquez Jul 23 '19 at 15:47
  • 2
    `unset` is not a function but a language construct (and a keyword). It must not and cannot be prefixed with `\` – hvertous Dec 03 '19 at 14:19
  • @ShivamSharma I’ve rolled back your edit — `array_values` was already mentioned, and your edit was thus making an already long answer substantially longer without adding new information. – Konrad Rudolph Feb 26 '20 at 10:29
  • @АртемНосов Please don’t remove the backslashes, they’re there for a reason. – Konrad Rudolph Jul 07 '20 at 19:11
  • 1
    This answer is wrong. Keys in an array by definition have a unique constraint, while elements do not. Functions like array_flip() and array_search() will not give you correct results if more than one element is that same. – Jed Lynch Oct 13 '20 at 14:34
  • @JedLynch The answer already addresses this case (last paragraph in particular). But I’ve made an example clearer and I’ve also removed the reference to `array_flip`, which I agree isn’t appropriate here. – Konrad Rudolph Oct 13 '20 at 16:30
  • 1
    What's with the backslashes in front of function names? – vanowm Nov 28 '21 at 22:19
  • @vanowm https://www.php.net/manual/en/language.namespaces.basics.php – Konrad Rudolph Nov 28 '21 at 22:59
  • 4
    Why have the backslashes? It's just confusing to anyone who doesn't know the meaning, and to anyone who does, they'll know if they need them anyway. Completely unnecessary IMO. – Clonkex Nov 08 '22 at 22:44
1420

It should be noted that unset() will keep indexes untouched, which is what you'd expect when using string indexes (array as hashtable), but can be quite surprising when dealing with integer indexed arrays:

$array = array(0, 1, 2, 3);
unset($array[2]);
var_dump($array);
/* array(3) {
  [0]=>
  int(0)
  [1]=>
  int(1)
  [3]=>
  int(3)
} */

$array = array(0, 1, 2, 3);
array_splice($array, 2, 1);
var_dump($array);
/* array(3) {
  [0]=>
  int(0)
  [1]=>
  int(1)
  [2]=>
  int(3)
} */

So array_splice() can be used if you'd like to normalize your integer keys. Another option is using array_values() after unset():

$array = array(0, 1, 2, 3);

unset($array[2]);
$array = array_values($array);
var_dump($array);
/* array(3) {
  [0]=>
  int(0)
  [1]=>
  int(1)
  [2]=>
  int(3)
} */
Ry-
  • 218,210
  • 55
  • 464
  • 476
Stefan Gehrig
  • 82,642
  • 24
  • 155
  • 189
  • 50
    It's worth noting that when you're using array_splice() you need to know the OFFSET, not the key, but the offset (!) of whatever element you wish to remove – Tom Jun 08 '12 at 21:57
  • 20
    @Tom: For a regular array (that's continuously integer-indexed) the offset is the index. That's where `array_splice` can make sense (amongst others). – Stefan Gehrig Jun 09 '12 at 12:18
  • 5
    Yes of course, but just something to remember if you tamper with the array before using splice – Tom Jun 09 '12 at 16:12
  • 1
    One question that would remains (and be awesome to be answered here) is **which one is better in term of performances ?** – Cyril N. Nov 17 '14 at 16:21
  • 4
    From just a basic test of deleting a ton of elements from a gigantic array, array_splice seems to be a lot quicker and less memory intensive. This matches with what I'd expect: array_values() seems to be making a copy of the array, while array_splice works in place. – Doug Kavendek Dec 01 '14 at 17:01
  • 4
    array_values is a useful approach when you are removing elements in a loop and want the indexes to be consistent, but then want to compress them out after the loop. – Rorrik Jun 02 '15 at 16:38
  • I think the sample array has not been chosen wisely, as the keys are equal to values – Peyman Mohamadpour Jul 20 '16 at 12:38
  • 1
    it makes sense that array_splice is faster or more efficient as it takes the offset and not the index to "choose" the elements that get deleted. Walking based on offsets rather than indexes saves you from reading each element's index – Javier Larroulet Sep 28 '18 at 16:55
  • Array_splice will only work for numeric arrays and so array_slice is not the best answer. – Jed Lynch Oct 13 '20 at 14:35
424
  // Our initial array
  $arr = array("blue", "green", "red", "yellow", "green", "orange", "yellow", "indigo", "red");
  print_r($arr);

  // Remove the elements who's values are yellow or red
  $arr = array_diff($arr, array("yellow", "red"));
  print_r($arr);

This is the output from the code above:

Array
(
    [0] => blue
    [1] => green
    [2] => red
    [3] => yellow
    [4] => green
    [5] => orange
    [6] => yellow
    [7] => indigo
    [8] => red
)

Array
(
    [0] => blue
    [1] => green
    [4] => green
    [5] => orange
    [7] => indigo
)

Now, array_values() will reindex a numerical array nicely, but it will remove all key strings from the array and replace them with numbers. If you need to preserve the key names (strings), or reindex the array if all keys are numerical, use array_merge():

$arr = array_merge(array_diff($arr, array("yellow", "red")));
print_r($arr);

Outputs

Array
(
    [0] => blue
    [1] => green
    [2] => green
    [3] => orange
    [4] => indigo
)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Marcel Cozma
  • 4,429
  • 1
  • 18
  • 17
  • $get_merged_values = array_merge($data['res'],$data['check_res']); when i print this print_r($get_merged_values); it displays the following. Array ( [0] => Array ( [menu_code] => 2 [menu_name] => Plant [menu_order_no] => 1 ) [1] => Array ( [menu_code] => 3 [menu_name] => Line [menu_order_no] => 2 ) ) But i need to get the values of menu_code and menu_name using $get_merged_values['menu_code'] and $get_merged_values['menu_name'] respectively, instead of using $get_merged_values[0][menu_code], $get_merged_values[0][menu_name]. please help me how to do this? – heart hacker Sep 20 '18 at 05:56
  • The phrasing of the question is misleading from how it is stated. This will not work if you want to delete $arr[$i] in a foreach loop if more than one element has the same value. – Jed Lynch Oct 13 '20 at 14:38
  • 1
    `array_merge(array_diff(` you saved my time, thanks for both the examples, `1.keys are not re-indexed` and `another one with keys are indexed again from 0...n` – Mohammed Sufian Aug 19 '22 at 15:21
238
$key = array_search($needle, $array);
if ($key !== false) {
    unset($array[$key]);
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
liamvictor
  • 3,251
  • 1
  • 22
  • 25
  • 9
    Would be good to clarify that this answer is for deleting an element, when you know the value, but not the key. Note that it only deletes the FIRST instance of the value; to find *all* keys for a value, use [array_keys](http://php.net/manual/en/function.array-keys.php) – ToolmakerSteve Sep 24 '16 at 18:09
  • If more than one element has the same value this will not work. – Jed Lynch Oct 13 '20 at 14:38
108
unset($array[$index]);
Eran Galperin
  • 86,251
  • 24
  • 115
  • 132
76

Also, for a named element:

unset($array["elementName"]);
Mohammad
  • 21,175
  • 15
  • 55
  • 84
DefenestrationDay
  • 3,712
  • 2
  • 33
  • 61
  • `$a = array("A"=>1, "B"=>2, "C"=>"a");` `print_r($a);` `unset($a["B"]);` `print_r($a);` gives (formatted): `Array ( [A] => 1 [B] => 2 [C] => a ), Array ( [A] => 1 [C] => a )` – DefenestrationDay Jun 09 '11 at 01:50
  • It seems you cannot unset array elements indexed by a string (generates "Fatal error: Cannot unset string offsets"). I dont think this was always the case, but certainly as of PHP 5.3.10 and probably earlier – carpii Apr 06 '12 at 00:29
  • 7
    @carpii PHP can unset elements from an associative array. The fatal error is caused when you try to use unset($var['key']) on a string instead of an array For example: $array = array( 'test' => 'value', 'another' => 'value', ); unset($array['test']); // Removes the "test" element from the array as expected $array = 'test'; unset($array['test']); // Throws "Fatal error: Cannot unset string offsets" as expected – Jimbo Mar 20 '13 at 09:56
  • Here you must know the key name, it's better: https://stackoverflow.com/a/52826684/1407491 – Nabi K.A.Z. Oct 16 '18 at 01:23
  • @Eran already recommended `unset()` back in 2008! If you wanted to improve that advice, you should have edited that answer. There is waaaaaaay too much redundant content on this multi-tabbed page! – mickmackusa Aug 23 '21 at 00:22
74

If you have a numerically indexed array where all values are unique (or they are non-unique but you wish to remove all instances of a particular value), you can simply use array_diff() to remove a matching element, like this:

$my_array = array_diff($my_array, array('Value_to_remove'));

For example:

$my_array = array('Andy', 'Bertha', 'Charles', 'Diana');
echo sizeof($my_array) . "\n";
$my_array = array_diff($my_array, array('Charles'));
echo sizeof($my_array);

This displays the following:

4
3

In this example, the element with the value 'Charles' is removed as can be verified by the sizeof() calls that report a size of 4 for the initial array, and 3 after the removal.

Robin Nixon
  • 751
  • 5
  • 2
39

Destroy a single element of an array

unset()

$array1 = array('A', 'B', 'C', 'D', 'E');
unset($array1[2]); // Delete known index(2) value from array
var_dump($array1);

The output will be:

array(4) {
  [0]=>
  string(1) "A"
  [1]=>
  string(1) "B"
  [3]=>
  string(1) "D"
  [4]=>
  string(1) "E"
}

If you need to re index the array:

$array1 = array_values($array1);
var_dump($array1);

Then the output will be:

array(4) {
  [0]=>
  string(1) "A"
  [1]=>
  string(1) "B"
  [2]=>
  string(1) "D"
  [3]=>
  string(1) "E"
}

Pop the element off the end of array - return the value of the removed element

mixed array_pop(array &$array)

$stack = array("orange", "banana", "apple", "raspberry");
$last_fruit = array_pop($stack);
print_r($stack);
print_r('Last Fruit:'.$last_fruit); // Last element of the array

The output will be

Array
(
    [0] => orange
    [1] => banana
    [2] => apple
)
Last Fruit: raspberry

Remove the first element (red) from an array, - return the value of the removed element

mixed array_shift ( array &$array )

$color = array("a" => "red", "b" => "green" , "c" => "blue");
$first_color = array_shift($color);
print_r ($color);
print_r ('First Color: '.$first_color);

The output will be:

Array
(
    [b] => green
    [c] => blue
)
First Color: red
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
KTAnj
  • 1,346
  • 14
  • 36
  • 1
    The `array_shift` re index the key items if it's integer, so it's bad, so you can use this: https://stackoverflow.com/a/52826684/1407491 – Nabi K.A.Z. Oct 16 '18 at 01:31
  • The complexity of [`array_shift()`](https://www.php.net/array_shift) is O(n) (due to re-indexing numeric indexes) and for [`array_pop()`](https://www.php.net/array_pop) it is O(1). How to get to know the first element's index? Just start a `foreach` and `break` it right in its first iteration. – AmigoJack Oct 23 '21 at 13:00
38
<?php
    $stack = ["fruit1", "fruit2", "fruit3", "fruit4"];
    $fruit = array_shift($stack);
    print_r($stack);

    echo $fruit;
?>

Output:

[
    [0] => fruit2
    [1] => fruit3
    [2] => fruit4
]

fruit1
Neha Sharma
  • 449
  • 5
  • 13
Saurabh Chandra Patel
  • 12,712
  • 6
  • 88
  • 78
30

If the index is specified:

$arr = ['a', 'b', 'c'];
$index = 0;    
unset($arr[$index]);  // $arr = ['b', 'c']

If we have value instead of index:

$arr = ['a', 'b', 'c'];

// search the value to find index
// Notice! this will only find the first occurrence of value
$index = array_search('a', $arr);

if($index !== false){
   unset($arr[$index]);  // $arr = ['b', 'c']
}

The if condition is necessary because if index is not found, unset() will automatically delete the first element of the array!!! which is not what we want.

Ahmad Mobaraki
  • 7,426
  • 5
  • 48
  • 69
  • 1
    `unset()` was already recommended on this page years earlier multiple times. `array_search()` with `unset()` was demonstrated back in 2011. https://stackoverflow.com/a/8135667/2943403 This answer add no new value to this page. – mickmackusa Aug 22 '21 at 02:46
  • @mickmackusa maybe you're right, all info in this answer can be found in other different answers. but maybe having it all in one answer for different conditions and explaining it simple, saves some time for someone. so it can be considered as value I guess! – Ahmad Mobaraki Aug 22 '21 at 03:34
  • That is one way to see it. The other way to see this multi-tab page is "severely over-bloated with redundant advice". Researchers have scroll through the same advice over and over to make sure that they are considering all relevant advice. Because answers are mixtures of single and multiple techniques AND many answers are saying the same thing -- the researcher experience is very much damaged. Imagine if you needed advice from this page. Would you want to read a novel full of redundant advice? I wouldn't. – mickmackusa Aug 22 '21 at 03:37
  • If you personally found previous answers to be "unclear" or needing more detail, you can edit those answers to better help researchers instead of posting a new answer. This means better advice distributed across fewer total answers. – mickmackusa Aug 22 '21 at 03:38
  • I agree with you in many cases. But I think purpose of editing an answer is fixing some words or minor technical typos not expanding/changing it. Anyway I myself spent some time to surf inside all answers and figure out a simple and effective way to do it, and came up with this solution and I felt maybe it's a good idea to share it. I think the reason it's getting some upvotes is that other people have the same situation and find this answer simple and understandable and covering! @mickmackusa – Ahmad Mobaraki Aug 22 '21 at 03:50
  • The problem with only paying attention to the vote tally is that it doesn't record the countless people who gave up reading other answers because of the "reader fatigue". By packing redundant information into more answers, it is harder for a new answer with unique insights to get noticed/read at all. Spare some consideration for the new/emerging answers that actually provide unique advice (posted and not yet posted). `If the index is NOT specified:` should actually say `If the value is specified:` -- then it should say that only the first occurrence is removed. – mickmackusa Aug 22 '21 at 04:00
  • @mickmackusa Thank you, sure I will. The reason I like to continue this discussion is that I care, and I did not posted this answer two years ago just for getting votes. I rarely post answers! I remember when I finally found what I want in this page (I was rookie at that time though!): 1- simply uset() 2- we have to first find index if we dont have it. 3- why we need to use if condition and not just passing array_search to unset()? I felt like I found the final correct and complete answer :))))) – Ahmad Mobaraki Aug 22 '21 at 04:13
  • I found Ahmad's reply very helpful. – oyvey Jun 11 '23 at 03:11
28

If you have to delete multiple values in an array and the entries in that array are objects or structured data, array_filter() is your best bet. Those entries that return a true from the callback function will be retained.

$array = [
    ['x'=>1,'y'=>2,'z'=>3], 
    ['x'=>2,'y'=>4,'z'=>6], 
    ['x'=>3,'y'=>6,'z'=>9]
];

$results = array_filter($array, function($value) {
    return $value['x'] > 2; 
}); //=> [['x'=>3,'y'=>6,z=>'9']]
Dharman
  • 30,962
  • 25
  • 85
  • 135
spyle
  • 1,960
  • 26
  • 23
25

If you need to remove multiple elements from an associative array, you can use array_diff_key() (here used with array_flip()):

$my_array = array(
  "key1" => "value 1",
  "key2" => "value 2",
  "key3" => "value 3",
  "key4" => "value 4",
  "key5" => "value 5",
);

$to_remove = array("key2", "key4");

$result = array_diff_key($my_array, array_flip($to_remove));

print_r($result);

Output:

Array ( [key1] => value 1 [key3] => value 3 [key5] => value 5 ) 
Simon
  • 3,580
  • 2
  • 23
  • 24
22

Associative arrays

For associative arrays, use unset:

$arr = array('a' => 1, 'b' => 2, 'c' => 3);
unset($arr['b']);

// RESULT: array('a' => 1, 'c' => 3)

Numeric arrays

For numeric arrays, use array_splice:

$arr = array(1, 2, 3);
array_splice($arr, 1, 1);

// RESULT: array(0 => 1, 1 => 3)

Note

Using unset for numeric arrays will not produce an error, but it will mess up your indexes:

$arr = array(1, 2, 3);
unset($arr[1]);

// RESULT: array(0 => 1, 2 => 3)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
John Slegers
  • 45,213
  • 22
  • 199
  • 169
21

unset() destroys the specified variables.

The behavior of unset() inside of a function can vary depending on what type of variable you are attempting to destroy.

If a globalized variable is unset() inside of a function, only the local variable is destroyed. The variable in the calling environment will retain the same value as before unset() was called.

<?php
    function destroy_foo()
    {
        global $foo;
        unset($foo);
    }

    $foo = 'bar';
    destroy_foo();
    echo $foo;
?>

The answer of the above code will be bar.

To unset() a global variable inside of a function:

<?php
    function foo()
    {
        unset($GLOBALS['bar']);
    }

    $bar = "something";
    foo();
?>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ankit Aggarwal
  • 360
  • 2
  • 10
19
// Remove by value
function removeFromArr($arr, $val)
{
    unset($arr[array_search($val, $arr)]);
    return array_values($arr);
}
Gigoland
  • 1,287
  • 13
  • 10
  • This code-only answer is not stable. If the targeted value is not found by `array_search()`, then its `false` return value will effectively remove the `[0]` keyed element which is not intended and is damaging to the input data. I will urge researchers not to use this snippet. – mickmackusa Aug 22 '21 at 02:44
15

Solutions:

  1. To delete one element, use unset():
unset($array[3]);
unset($array['foo']);
  1. To delete multiple noncontiguous elements, also use unset():
unset($array[3], $array[5]);
unset($array['foo'], $array['bar']);
  1. To delete multiple contiguous elements, use array_splice():
array_splice($array, $offset, $length);

Further explanation:

Using these functions removes all references to these elements from PHP. If you want to keep a key in the array, but with an empty value, assign the empty string to the element:

$array[3] = $array['foo'] = '';

Besides syntax, there's a logical difference between using unset() and assigning '' to the element. The first says This doesn't exist anymore, while the second says This still exists, but its value is the empty string.

If you're dealing with numbers, assigning 0 may be a better alternative. So, if a company stopped production of the model XL1000 sprocket, it would update its inventory with:

unset($products['XL1000']);

However, if it temporarily ran out of XL1000 sprockets, but was planning to receive a new shipment from the plant later this week, this is better:

$products['XL1000'] = 0;

If you unset() an element, PHP adjusts the array so that looping still works correctly. It doesn't compact the array to fill in the missing holes. This is what we mean when we say that all arrays are associative, even when they appear to be numeric. Here's an example:

// Create a "numeric" array
$animals = array('ant', 'bee', 'cat', 'dog', 'elk', 'fox');
print $animals[1];  // Prints 'bee'
print $animals[2];  // Prints 'cat'
count($animals);    // Returns 6

// unset()
unset($animals[1]); // Removes element $animals[1] = 'bee'
print $animals[1];  // Prints '' and throws an E_NOTICE error
print $animals[2];  // Still prints 'cat'
count($animals);    // Returns 5, even though $array[5] is 'fox'

// Add a new element
$animals[ ] = 'gnu'; // Add a new element (not Unix)
print $animals[1];  // Prints '', still empty
print $animals[6];  // Prints 'gnu', this is where 'gnu' ended up
count($animals);    // Returns 6

// Assign ''
$animals[2] = '';   // Zero out value
print $animals[2];  // Prints ''
count($animals);    // Returns 6, count does not decrease

To compact the array into a densely filled numeric array, use array_values():

$animals = array_values($animals);

Alternatively, array_splice() automatically reindexes arrays to avoid leaving holes:

// Create a "numeric" array
$animals = array('ant', 'bee', 'cat', 'dog', 'elk', 'fox');
array_splice($animals, 2, 2);
print_r($animals);
Array
(
    [0] => ant
    [1] => bee
    [2] => elk
    [3] => fox
)

This is useful if you're using the array as a queue and want to remove items from the queue while still allowing random access. To safely remove the first or last element from an array, use array_shift() and array_pop(), respectively.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Star
  • 3,222
  • 5
  • 32
  • 48
14

Follow the default functions:

  • PHP: unset

unset() destroys the specified variables. For more info, you can refer to PHP unset

$Array = array("test1", "test2", "test3", "test3");

unset($Array[2]);
  • PHP: array_pop

The array_pop() function deletes the last element of an array. For more info, you can refer to PHP array_pop

$Array = array("test1", "test2", "test3", "test3");

array_pop($Array);
  • PHP: array_splice

The array_splice() function removes selected elements from an array and replaces it with new elements. For more info, you can refer to PHP array_splice

$Array = array("test1", "test2", "test3", "test3");

array_splice($Array,1,2);
  • PHP: array_shift

The array_shift() function removes the first element from an array. For more info, you can refer to PHP array_shift

$Array = array("test1", "test2", "test3", "test3");

array_shift($Array);
Rabby
  • 322
  • 4
  • 15
msvairam
  • 862
  • 5
  • 12
11

I'd just like to say I had a particular object that had variable attributes (it was basically mapping a table and I was changing the columns in the table, so the attributes in the object, reflecting the table would vary as well):

class obj {
    protected $fields = array('field1','field2');
    protected $field1 = array();
    protected $field2 = array();
    protected loadfields(){}
    // This will load the $field1 and $field2 with rows of data for the column they describe
    protected function clearFields($num){
        foreach($fields as $field) {
            unset($this->$field[$num]);
            // This did not work the line below worked
            unset($this->{$field}[$num]); // You have to resolve $field first using {}
        }
    }
}

The whole purpose of $fields was just, so I don't have to look everywhere in the code when they're changed, I just look at the beginning of the class and change the list of attributes and the $fields array content to reflect the new attributes.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Oxydel
  • 176
  • 1
  • 5
10

Two ways for removing the first item of an array with keeping order of the index and also if you don't know the key name of the first item.

Solution #1

// 1 is the index of the first object to get
// NULL to get everything until the end
// true to preserve keys
$array = array_slice($array, 1, null, true);

Solution #2

// Rewinds the array's internal pointer to the first element
// and returns the value of the first array element.
$value = reset($array);
// Returns the index element of the current array position
$key = key($array);
unset($array[$key]);

For this sample data:

$array = array(10 => "a", 20 => "b", 30 => "c");

You must have this result:

array(2) {
  [20]=>
  string(1) "b"
  [30]=>
  string(1) "c"
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Nabi K.A.Z.
  • 9,887
  • 6
  • 59
  • 81
  • 3
    `array_slice()` and `unset()` were already demonstrated many times before you posted your answer. This answer is redundant and is only damaging the researcher experience. – mickmackusa Aug 22 '21 at 02:54
  • 1
    @mickmackusa But my answer was clean and clear. – Nabi K.A.Z. Aug 23 '21 at 05:35
  • 1
    ...and redundant. You haven't added any unique value to this page that is specific to element deletion. You've trailed off-topic to talk about how to target the first element's key. The OP makes no mention of wanting to target the first element. You've likely been tricked into a different scope by reading other answers in this very over crowded page. This answer is safely removed for the sake of improving the researcher experience. – mickmackusa Aug 23 '21 at 05:54
9

Edit

If you can't take it as given that the object is in that array you need to add a check:

if(in_array($object,$array)) unset($array[array_search($object,$array)]);

Original Answer

if you want to remove a specific object of an array by reference of that object you can do following:

unset($array[array_search($object,$array)]);

Example:

<?php
class Foo
{
    public $id;
    public $name;
}

$foo1 = new Foo();
$foo1->id = 1;
$foo1->name = 'Name1';

$foo2 = new Foo();
$foo2->id = 2;
$foo2->name = 'Name2';

$foo3 = new Foo();
$foo3->id = 3;
$foo3->name = 'Name3';


$array = array($foo1,$foo2,$foo3);
unset($array[array_search($foo2,$array)]);

echo '<pre>';
var_dump($array);
echo '</pre>';
?>

Result:

array(2) {
[0]=>
    object(Foo)#1 (2) {
        ["id"]=>
        int(1)
        ["name"]=>
        string(5) "Name1"
    }
[2]=>
    object(Foo)#3 (2) {
        ["id"]=>
        int(3)
        ["name"]=>
        string(5) "Name3"
    }
}

Note that if the object occures several times it will only be removed the first occurence!

Sam Tigle
  • 393
  • 3
  • 14
  • This answer is not stable. If the targeted array key is not found by `array_search()` then its return value will effectively destroy the `[0]` keyed element. This snippet is dangerous and should be removed. There were earlier answers that do not make this mistake. – mickmackusa Aug 22 '21 at 03:00
  • @mickmackusa thanks for the hint, added a check – Sam Tigle Aug 24 '21 at 10:08
  • Doing a potentially full scan of the array with `in_array()` then another potentially full scan again with `array_search()` is definitely not something that I would recommend to anyone. This is simply bad practice. My stance remains -- this answer makes mistakes that earlier answers did not make. Correcting this answer will only make it redundant of earlier answers. This page will be improved if this answer is removed. – mickmackusa Aug 24 '21 at 10:27
8

unset() multiple, fragmented elements from an array

While unset() has been mentioned here several times, it has yet to be mentioned that unset() accepts multiple variables making it easy to delete multiple, noncontiguous elements from an array in one operation:

// Delete multiple, noncontiguous elements from an array
$array = [ 'foo', 'bar', 'baz', 'quz' ];
unset( $array[2], $array[3] );
print_r($array);
// Output: [ 'foo', 'bar' ]

unset() dynamically

unset() does not accept an array of keys to remove, so the code below will fail (it would have made it slightly easier to use unset() dynamically though).

$array = range(0,5);
$remove = [1,2];
$array = unset( $remove ); // FAILS: "unexpected 'unset'"
print_r($array);

Instead, unset() can be used dynamically in a foreach loop:

$array = range(0,5);
$remove = [1,2];
foreach ($remove as $k=>$v) {
    unset($array[$v]);
}
print_r($array);
// Output: [ 0, 3, 4, 5 ]

Remove array keys by copying the array

There is also another practice that has yet to be mentioned. Sometimes, the simplest way to get rid of certain array keys is to simply copy $array1 into $array2.

$array1 = range(1,10);
foreach ($array1 as $v) {
    // Remove all even integers from the array
    if( $v % 2 ) {
        $array2[] = $v;
    }
}
print_r($array2);
// Output: [ 1, 3, 5, 7, 9 ];

Obviously, the same practice applies to text strings:

$array1 = [ 'foo', '_bar', 'baz' ];
foreach ($array1 as $v) {
    // Remove all strings beginning with underscore
    if( strpos($v,'_')===false ) {
        $array2[] = $v;
    }
}
print_r($array2);
// Output: [ 'foo', 'baz' ]
Star
  • 3,222
  • 5
  • 32
  • 48
Kristoffer Bohmann
  • 3,986
  • 3
  • 28
  • 35
7
<?php
    // If you want to remove a particular array element use this method
    $my_array = array("key1"=>"value 1", "key2"=>"value 2", "key3"=>"value 3");

    print_r($my_array);
    if (array_key_exists("key1", $my_array)) {
        unset($my_array['key1']);
        print_r($my_array);
    }
    else {
        echo "Key does not exist";
    }
?>

<?php
    //To remove first array element
    $my_array = array("key1"=>"value 1", "key2"=>"value 2", "key3"=>"value 3");
    print_r($my_array);
    $new_array = array_slice($my_array, 1);
    print_r($new_array);
?>


<?php
    echo "<br/>    ";
    // To remove first array element to length
    // starts from first and remove two element
    $my_array = array("key1"=>"value 1", "key2"=>"value 2", "key3"=>"value 3");
    print_r($my_array);
    $new_array = array_slice($my_array, 1, 2);
    print_r($new_array);
?>

Output

 Array ( [key1] => value 1 [key2] => value 2 [key3] =>
 value 3 ) Array (    [key2] => value 2 [key3] => value 3 )
 Array ( [key1] => value 1 [key2] => value 2 [key3] => value 3 )
 Array ( [key2] => value 2 [key3] => value 3 )
 Array ( [key1] => value 1 [key2] => value 2 [key3] => value 3 )
 Array ( [key2] => value 2 [key3] => value 3 )
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Umar Farooque Khan
  • 515
  • 1
  • 6
  • 17
  • It is not beneficial to check if a key exists before calling `unset()`. If the key is not found in the array, then `unset()` will silently do nothing (as expected). `unset()` and `array_slice()` were already recommended before this answer was posted. This answer adds no new value to this page. – mickmackusa Aug 22 '21 at 02:57
7

Remove an array element based on a key:

Use the unset function like below:

$a = array(
       'salam',
       '10',
       1
);

unset($a[1]);

print_r($a);

/*

    Output:

        Array
        (
            [0] => salam
            [2] => 1
        )

*/

Remove an array element based on value:

Use the array_search function to get an element key and use the above manner to remove an array element like below:

$a = array(
       'salam',
       '10',
       1
);

$key = array_search(10, $a);

if ($key !== false) {
    unset($a[$key]);
}

print_r($a);

/*

    Output:

        Array
        (
            [0] => salam
            [2] => 1
        )

*/
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
MahdiY
  • 1,269
  • 21
  • 32
  • 1
    `unset()` and `array_search()` with `unset()` was already posted by 2017. This answer is only providing redundant insights. – mickmackusa Aug 22 '21 at 02:56
6

Use the following code:

$arr = array('orange', 'banana', 'apple', 'raspberry');
$result = array_pop($arr);
print_r($result);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
2

I came here because I wanted to see if there was a more elegant solution to this problem than using unset($arr[$i]). To my disappointment these answers are either wrong or do not cover every edge case.

Here is why array_diff() does not work. Keys are unique in the array, while elements are not always unique.

$arr = [1,2,2,3];

foreach($arr as $i => $n){
    $b = array_diff($arr,[$n]);
    echo "\n".json_encode($b);
}

Results...

[2,2,3]
[1,3]
[1,2,2] 

If two elements are the same they will be remove. This also applies for array_search() and array_flip().

I saw a lot of answers with array_slice() and array_splice(), but these functions only work with numeric arrays. All the answers I am aware if here does not answer the question, and so here is a solution that will work.

$arr = [1,2,3];

foreach($arr as $i => $n){
    $b = array_merge(array_slice($arr,0,$i),array_slice($arr,$i+1));
    echo "\n".json_encode($b);
}

Results...

[2,3];
[1,3];
[1,2];

Since unset($arr[$i]) will work on both associative array and numeric arrays this still does not answer the question.

This solution is to compare the keys and with a tool that will handle both numeric and associative arrays. I use array_diff_uassoc() for this. This function compares the keys in a call back function.

$arr = [1,2,2,3];
//$arr = ['a'=>'z','b'=>'y','c'=>'x','d'=>'w'];
foreach($arr as $key => $n){
    $b = array_diff_uassoc($arr, [$key=>$n], function($a,$b) {
        if($a != $b){
            return 1;
        }
    });
    echo "\n".json_encode($b);
}    

Results.....

[2,2,3];
[1,2,3];
[1,2,2];

['b'=>'y','c'=>'x','d'=>'w'];
['a'=>'z','c'=>'x','d'=>'w'];
['a'=>'z','b'=>'y','d'=>'w'];
['a'=>'z','b'=>'y','c'=>'x'];
Jed Lynch
  • 1,998
  • 18
  • 14