Categories
arrays php unset

Deleting an element from an array in PHP

2909

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.

7

  • 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, 2012 at 17:05

  • 42

    @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.

    Feb 11, 2014 at 5:18


  • 7

    @unset($array[$key]); $array = array_values($array);

    – trojan

    Sep 4, 2014 at 12:55

  • 2

    If you want to remove keys from array of array (Associative array), see solution at stackoverflow.com/a/47978980/1045444

    Dec 26, 2017 at 13:10

  • 2

    you can do it in a foreach loop like this: pastefs.com/pid/130950

    – Aurangzeb

    Jun 25, 2019 at 10:50


3379

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 array element you can use unset() or alternatively \array_splice().

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 does not occur more than once, since \array_search returns the first hit only.

unset()

Note that 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.

Code:

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

Output:

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

\array_splice() method

If you use \array_splice() the keys will automatically be reindexed, but the associative keys won’t change — as opposed to \array_values(), which will convert all keys to numerical keys.

\array_splice() needs the offset, not the key, as the second parameter.

Code:

$array = [0 => "a", 1 => "b", 2 => "c"];
\array_splice($array, 1, 1);
                   // ↑ Offset which you want to delete

Output:

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

array_splice(), same as unset(), take the array by reference. You don’t assign the return values of those functions 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 which you want to delete.

\array_diff() method

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.

Code:

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

Output:

[
    [1] => b
]

\array_diff_key() method

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.

Code:

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

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() method

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

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
});

Output:

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

15

  • 29

    @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.

    Jun 13, 2012 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, 2016 at 5:33


  • 9

    unset can have multiple arguments: void unset ( mixed $var [, mixed $... ] ).

    Apr 14, 2017 at 3: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. php.net/manual/en/function.json-encode.php#94157

    May 6, 2017 at 0:20

  • 2

    unset is not a function but a language construct (and a keyword). It must not and cannot be prefixed with “

    – hvertous

    Dec 3, 2019 at 14:19

1401

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)
} */

9

  • 48

    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 8, 2012 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).

    Jun 9, 2012 at 12:18

  • 5

    Yes of course, but just something to remember if you tamper with the array before using splice

    – Tom

    Jun 9, 2012 at 16:12

  • 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.

    Dec 1, 2014 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 2, 2015 at 16:38

408

  // 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
)

2

  • $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?

    Sep 20, 2018 at 5: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, 2020 at 14:38