PHP example

How to remove an element from an array in PHP

8 min read Updated Dec 2026 Runs in an isolated runtime
Quick answer

Use unset($array[$key]). It removes the element by key and leaves every other key as it was, so removing key 1 from a list leaves the keys 0, 2, 3; call array_values() to renumber it. To remove by position and renumber in one step, use array_splice($array, $index, 1). To remove by value, find the key with array_search($value, $array, true) and check it with !== false before you unset it, or drop every match with array_diff($array, [$value]).

A PHP array is an ordered map: every element has a key, and a "list" is just an array whose keys happen to be 0, 1, 2…. That is why removing an element has more than one answer. unset deletes a key and leaves the rest alone, array_splice works by position and renumbers, and the array_* functions build a new array without the values you name. The sections below cover removing by key, by position and by value, taking the first or last item, dropping several keys at once and removing items inside a loop, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.

1unset by key, then array_valuesRecommended

unset($array[$key]) is the direct answer: it removes one element in place and works the same for integer and string keys. It does not renumber the remaining keys. For an associative array that is what you want; for a list it leaves a gap, and the gap shows up later, most visibly in json_encode, which turns a list with gaps into a JSON object. Pass the result through array_values() when you need a clean list again.

unset.php
<?php

$fruits = ['apple', 'banana', 'cherry', 'date'];
unset($fruits[1]);
print_r($fruits);

// The other keys are kept, so the list now has a gap at 1
var_dump(array_is_list($fruits));
echo json_encode($fruits), "\n";

// array_values renumbers from 0, and JSON is an array again
$fruits = array_values($fruits);
print_r($fruits);
echo json_encode($fruits), "\n";

// String keys work the same way
$user = ['name' => 'Ada', 'email' => '[email protected]', 'age' => 36];
unset($user['email']);
echo json_encode($user), "\n";

// Unsetting a key that isn't there is not an error
unset($user['phone']);
echo count($user), "\n";

// The next append still continues after the old highest key
$nums = [10, 20, 30];
unset($nums[2]);
$nums[] = 40;
echo json_encode($nums), "\n";

Output

After unset($fruits[1]) the keys are 0, 2 and 3, array_is_list (PHP 8.1) returns bool(false), and json_encode prints {"0":"apple","2":"cherry","3":"date"}: an object, not an array, which breaks JavaScript code that expects a list. After array_values the keys are 0, 1, 2 and the JSON is ["apple","cherry","date"]. Unsetting a missing key is silent, and the last line shows that PHP remembers the highest key it has used: after removing key 2, $nums[] = 40 lands at key 3.

2array_splice by position

array_splice($array, $offset, $length) removes elements by position, not by key, renumbers the integer keys, and returns what it took out. That makes it the natural choice for a list when you know the index and want no gap. The length lets it remove a range, a negative offset counts from the end, and a fourth argument inserts replacements in the same call. It changes the array you pass; for a copy without one item, combine two array_slice calls.

splice.php
<?php

function show(array $a): void
{
    $pairs = [];
    foreach ($a as $k => $v) {
        $pairs[] = var_export($k, true) . ' => ' . var_export($v, true);
    }
    echo '[', implode(', ', $pairs), "]\n";
}

$letters = ['a', 'b', 'c', 'd', 'e', 'f'];

// Remove 1 item at position 1; the list is renumbered
$removed = array_splice($letters, 1, 1);
show($letters);
show($removed);

// Remove a range: 2 items starting at position 2
array_splice($letters, 2, 2);
show($letters);

// A negative offset counts from the end
$queue = [1, 2, 3, 4, 5];
array_splice($queue, -2, 1);
show($queue);

// Without a length it removes everything from the offset on
$queue = [1, 2, 3, 4, 5];
$tail = array_splice($queue, 3);
show($queue);
show($tail);

// Remove and insert in one call
$colors = ['red', 'green', 'blue'];
array_splice($colors, 1, 1, ['lime', 'teal']);
show($colors);

// Position, not key: string keys are kept, integer keys renumbered
$mixed = [5 => 'x', 'id' => 7, 9 => 'y', 10 => 'z'];
array_splice($mixed, 0, 1);
show($mixed);

// A copy without position 1; the original is untouched
$orig = ['a', 'b', 'c'];
$copy = [...array_slice($orig, 0, 1), ...array_slice($orig, 2)];
show($orig);
show($copy);

Output

Removing position 1 leaves [0 => 'a', 1 => 'c', …] with no gap, and the return value is the removed part as an array, [0 => 'b'], not the bare value. The $mixed line shows the rule exactly: the offset counts positions, so array_splice($mixed, 0, 1) removed key 5, the string key 'id' stayed, and 9 and 10 became 0 and 1. On an associative array, use unset with the key instead.

3Removing by value: array_search, array_diff, array_filter

When you know the value but not the key, there are two cases. For the first match, get its key with array_search($value, $array, true) and unset it. array_search returns false when nothing matches, and a match at key 0 returns 0, so compare with !== false. For every match, array_diff returns the array without the values you list, and array_filter does the same with a callback, which is the way to get a strict comparison. All three keep the original keys.

by_value.php
<?php

function show(array $a): void
{
    $pairs = [];
    foreach ($a as $k => $v) {
        $pairs[] = var_export($k, true) . ' => ' . var_export($v, true);
    }
    echo '[', implode(', ', $pairs), "]\n";
}

// First match: find its key, then unset it
$tags = ['php', 'js', 'go', 'js'];
$key = array_search('js', $tags, true);
if ($key !== false) {
    unset($tags[$key]);
}
show($tags);

// Trap 1: a match at key 0 is falsy, so "if ($key)" skips it
$tags = ['php', 'js', 'go'];
$key = array_search('php', $tags, true);
var_dump($key);
if ($key) {
    unset($tags[$key]);
}
show($tags);

// Trap 2: no check at all; false is used as key 0
$tags = ['php', 'js', 'go'];
$key = array_search('rust', $tags, true);
unset($tags[$key]);
show($tags);

// Every match: array_diff removes all values in the second array
$tags = ['php', 'js', 'go', 'js'];
show(array_diff($tags, ['js']));
show(array_values(array_diff($tags, ['js', 'go'])));

// array_diff compares as strings, so 1, '1', 1.0 and true all go
$ids = [1, '1', 2, 1.0, true];
show(array_diff($ids, [1]));

// array_filter with !== removes only the exact int 1
show(array_filter($ids, fn($v) => $v !== 1));

// Without strict mode, array_search compares loosely
var_dump(array_search('1e1', ['10', '1e1']));
var_dump(array_search('1e1', ['10', '1e1'], true));

Output

array_search removed only the first 'js'; the second one at key 3 is still there. The two traps are both silent: if ($key) saw int(0) as false and removed nothing, and unsetting with an unchecked false for a missing value deleted 'php' at key 0, because false used as a key becomes 0. array_diff($ids, [1]) left only [2 => 2] since it compares string forms, while the !== filter kept '1', 1.0 and true. The last two lines show why the third argument of array_search matters: loosely, '1e1' equals the numeric string '10' and matches at int(0).

4The first or last element: array_shift and array_pop

array_pop removes the last element and returns it; array_shift does the same for the first. Both change the array in place and return null when it is empty. They differ in what happens to the keys: array_shift renumbers every integer key from 0, even on an array whose keys mean something, while string keys stay. To drop the first element and keep the keys, unset array_key_first($array) (PHP 7.3) instead. To read the first or last item without removing it, see getting the first and last element.

shift_pop.php
<?php

function show(array $a): void
{
    $pairs = [];
    foreach ($a as $k => $v) {
        $pairs[] = var_export($k, true) . ' => ' . var_export($v, true);
    }
    echo '[', implode(', ', $pairs), "]\n";
}

$stack = ['a', 'b', 'c', 'd'];

// array_pop removes and returns the last item
$last = array_pop($stack);
echo $last, "\n";
show($stack);

// array_shift removes and returns the first item
$first = array_shift($stack);
echo $first, "\n";
show($stack);

// Both return null on an empty array
$empty = [];
var_dump(array_pop($empty), array_shift($empty));

// array_shift renumbers integer keys, string keys stay
$scores = [10 => 'x', 20 => 'y', 'top' => 'z', 30 => 'w'];
array_shift($scores);
show($scores);

// array_pop leaves the other keys alone
$scores = [10 => 'x', 20 => 'y', 30 => 'w'];
array_pop($scores);
show($scores);

// To keep the keys, unset the first key instead
$scores = [10 => 'x', 20 => 'y', 30 => 'w'];
unset($scores[array_key_first($scores)]);
show($scores);

Output

The pair works as a stack (array_pop returned d) and a queue (array_shift returned a), and both returned NULL on the empty array, so a null stored in the array looks the same as "nothing left"; check count() or empty() first when that matters. On $scores, array_shift turned keys 20 and 30 into 0 and 1 while 'top' stayed; array_pop and the array_key_first version kept 20 and 30. array_shift also has to renumber the whole array each call, so on a large queue SplQueue is the faster choice.

5Several keys at once: unset and array_diff_key

unset takes any number of arguments, so unset($a['x'], $a['y']) removes two keys in one statement. When the keys come from a list, array_diff_key returns a new array without them: flip the list with array_flip so the names become keys. The opposite, keeping only an allow-list of keys, is array_intersect_key, and array_filter with ARRAY_FILTER_USE_KEY removes keys that match a rule.

several_keys.php
<?php

function show(array $a): void
{
    $pairs = [];
    foreach ($a as $k => $v) {
        $pairs[] = var_export($k, true) . ' => ' . var_export($v, true);
    }
    echo '[', implode(', ', $pairs), "]\n";
}

$user = [
    'id' => 7,
    'name' => 'Ada',
    'password' => 'hunter2',
    'token' => 'abc123',
    'email' => '[email protected]',
];

// unset takes several elements at once
$copy = $user;
unset($copy['password'], $copy['token']);
show($copy);

// array_diff_key: a new array without a list of keys
$hidden = ['password', 'token', 'ssn'];
$public = array_diff_key($user, array_flip($hidden));
show($public);

// The opposite: keep only the listed keys
$allowed = ['id', 'name'];
show(array_intersect_key($user, array_flip($allowed)));

// array_filter with ARRAY_FILTER_USE_KEY for a rule
show(array_filter(
    $user,
    fn(string $k) => !str_starts_with($k, 'pass'),
    ARRAY_FILTER_USE_KEY,
));

// Several positions in a list: unset each, then renumber once
$items = ['a', 'b', 'c', 'd', 'e'];
foreach ([1, 3] as $i) {
    unset($items[$i]);
}
show(array_values($items));

Output

Both ways of dropping password and token give the same three keys, and array_diff_key did not mind that 'ssn' is not in the array. The filter removed only password, the one key starting with pass. The last line removes positions 1 and 3 by unsetting them first and renumbering once at the end; doing it with array_splice one at a time would shift position 3 to 2 after the first removal and delete the wrong item.

6Removing items while looping

A foreach by value walks a snapshot of the array, so unsetting $array[$key] inside it is safe: the loop still visits every original element. The bugs come from for loops over positions. Removing with array_splice shifts the next item into the current index, which the $i++ then skips, and unsetting with $i < count($array) stops early because the count shrinks while $i grows. In most code, array_filter replaces the loop altogether.

remove_in_loop.php
<?php

function show(array $a): void
{
    $pairs = [];
    foreach ($a as $k => $v) {
        $pairs[] = var_export($k, true) . ' => ' . var_export($v, true);
    }
    echo '[', implode(', ', $pairs), "]\n";
}

// Safe: foreach by value walks a snapshot, unset the real array by key
$nums = [2, 4, 5, 6, 7, 8];
foreach ($nums as $i => $n) {
    if ($n % 2 === 0) {
        unset($nums[$i]);
    }
}
show($nums);

// Shorter: array_filter keeps the items the callback returns true for
$nums = [2, 4, 5, 6, 7, 8];
show(array_filter($nums, fn(int $n) => $n % 2 !== 0));

// Bug 1: array_splice in a for loop skips the item after each removal
$nums = [2, 4, 5, 6, 7, 8];
for ($i = 0; $i < count($nums); $i++) {
    if ($nums[$i] % 2 === 0) {
        array_splice($nums, $i, 1);
    }
}
show($nums);

// Fix: walk backwards, so removals don't shift what is left to visit
$nums = [2, 4, 5, 6, 7, 8];
for ($i = count($nums) - 1; $i >= 0; $i--) {
    if ($nums[$i] % 2 === 0) {
        array_splice($nums, $i, 1);
    }
}
show($nums);

// Bug 2: unset in a for loop shrinks count() while $i keeps going
$letters = ['a', 'b', 'c', 'd'];
for ($i = 0; $i < count($letters); $i++) {
    unset($letters[$i]);
}
show($letters);

Output

The foreach and the array_filter call both leave [2 => 5, 4 => 7], with the original keys; add array_values for a fresh list. The forward for loop kept 4, because after 2 was spliced out, 4 moved to index 0 and the loop had already moved on to 1; walking backwards gives the right [0 => 5, 1 => 7]. Bug 2 cleared only two of the four letters. If you loop by reference (foreach ($a as &$v)), call unset($v) after the loop: the variable stays a reference to the last element, and a later foreach ($a as $v) on [10, 20, 30] overwrites it, leaving [10,20,20].

7Which should you use?

MethodRemoves byKeys afterwardsBest for
unset($a[$k])KeyKept (gaps in a list)Most cases; add array_values for a list
array_splice($a, $i, $n)PositionInteger keys renumberedLists, ranges, getting the removed items
array_search + unsetValue, first matchKeptOne occurrence; check !== false
array_diff / array_filterValue, every matchKeptAll occurrences; array_filter for strict
array_shift / array_popFirst / lastshift renumbers, pop keepsQueues and stacks
array_diff_keyList of keysKeptDropping fields from a record

Frequently asked questions

Why does json_encode return an object after I unset an element?

json_encode writes a JSON array only when the keys are exactly 0, 1, 2… in order. After unset($a[1]) the keys are 0, 2, 3, so it writes {"0":"apple","2":"cherry","3":"date"}. Renumber first: json_encode(array_values($a)) gives ["apple","cherry","date"]. array_is_list($a) (PHP 8.1) tells you which one you will get.

How do I delete an element from an array by value, not by key?

For the first match, $k = array_search($value, $a, true); if ($k !== false) { unset($a[$k]); }. For every match, $a = array_diff($a, [$value]);, or array_filter($a, fn($v) => $v !== $value) when the comparison must be strict. Wrap the result in array_values() if you need the keys renumbered.

What is the difference between unset and array_splice?

unset($a[$k]) removes by key, keeps every other key as it was and returns nothing. array_splice($a, $i, 1) removes by position, renumbers the integer keys (string keys are kept) and returns the removed elements as an array. Use unset for associative arrays and array_splice for lists where you want no gap.

Why did unset with array_search remove the first element of my array?

The value was not in the array, so array_search returned false, and false used as an array key is converted to 0. unset($a[false]) therefore removes key 0. Always compare the result with !== false before unsetting; a plain if ($key) is wrong too, because it skips a real match at key 0.

Is it safe to unset array elements inside a foreach loop?

Yes, when you loop by value and unset by key: foreach ($a as $k => $v) { if (...) unset($a[$k]); }. The loop walks a snapshot, so every original element is visited. Removing by position in a for loop is what goes wrong, because the indexes shift; loop backwards or use array_filter instead.

How do I remove an item from an array of arrays or objects by a field?

Use array_filter with a callback that reads the field: $users = array_filter($users, fn($u) => $u['id'] !== 7); for arrays, or $u->id for objects. It returns a new array with the original keys, so add array_values() if the result goes to json_encode as a list.

Run it yourself

Open any of these in the full PHP editor to tweak, run and share.

PHP playground