Remove Array Items

Ma Mahalakshmi V Updated 14 Nov 2026
7 min read ·Lesson 84 of 255

Removing elements from an array can mean several different things: deleting a specific key, taking the last or first element, cutting out a range, removing every occurrence of a value, or keeping only elements that pass a test. PHP has a dedicated tool for each, and they differ in one important way — whether the remaining keys are kept or re-numbered.

TaskFunctionKeys After Removal
Remove by keyunset($array[$key])Kept (gaps remain)
Remove a range by positionarray_splice()Re-numbered
Remove and return the last elementarray_pop()—
Remove and return the first elementarray_shift()Re-numbered (integer keys)
Remove all occurrences of valuesarray_diff()Kept
Remove specific keysarray_diff_key()Kept
Remove elements failing a conditionarray_filter()Kept
Remove duplicatesarray_unique()Kept (first occurrence)

unset() — Remove by Key

Example

<?php
$colors = ['red', 'green', 'blue', 'yellow'];

unset($colors[1]);

print_r($colors);
echo count($colors) . " colors left\n";

Output

Array
(
    [0] => red
    [2] => blue
    [3] => yellow
)
3 colors left

How It Works

  • unset() removes the element with key 1 from the array.
  • The remaining elements keep their original keys, so the list now has a gap (0, 2, 3).
  • unset() on a key that does not exist does nothing — no warning.

Removing Several Keys at Once

<?php
$user = ['id' => 7, 'name' => 'Asha', 'password' => 'secret', 'token' => 'abc123'];

unset($user['password'], $user['token']);

print_r($user);

Output

Array
(
    [id] => 7
    [name] => Asha
)

unset() accepts several arguments. For associative arrays, gaps are not a concern — keys are names, not positions.

Re-indexing After unset()

<?php
$colors = ['red', 'green', 'blue', 'yellow'];
unset($colors[1]);

$colors = array_values($colors);

print_r($colors);

Output

Array
(
    [0] => red
    [1] => blue
    [2] => yellow
)

Re-index lists with array_values() when continuous indexes matter — for for loops, for json_encode() (which turns gapped lists into JSON objects), or for index-based access.


array_splice() — Remove by Position

<?php
$colors = ['red', 'green', 'blue', 'yellow'];

$removed = array_splice($colors, 1, 2);

echo 'Remaining: ' . implode(', ', $colors) . "\n";
echo 'Removed: ' . implode(', ', $removed) . "\n";
print_r($colors);

Output

Remaining: red, yellow
Removed: green, blue
Array
(
    [0] => red
    [1] => yellow
)

array_splice($array, $offset, $length):

  • removes $length elements starting at position $offset,
  • re-indexes the remaining list,
  • returns the removed elements.

A negative offset counts from the end: array_splice($list, -1) removes the last element. Note that $offset is a position, not a key — for lists with gaps, position and key can differ.


array_pop() and array_shift() — Take From the Ends

<?php
$tasks = ['first', 'second', 'third'];

$last = array_pop($tasks);
$first = array_shift($tasks);

echo "Popped: $last\n";
echo "Shifted: $first\n";
print_r($tasks);

$empty = [];
var_dump(array_pop($empty));

Output

Popped: third
Shifted: first
Array
(
    [0] => second
)
NULL
FunctionRemovesReturnsTypical Use
array_pop()Last elementThe removed valueStacks (last in, first out)
array_shift()First elementThe removed valueQueues (first in, first out)

Both return null for an empty array. array_shift() re-indexes integer keys, which makes it slower than array_pop() on very large arrays.


Removing by Value

The First Occurrence: array_search() + unset()

<?php
$cart = ['Pen', 'Notebook', 'Pen', 'Eraser'];

$position = array_search('Pen', $cart, true);

if ($position !== false) {
    unset($cart[$position]);
}

echo implode(', ', $cart) . "\n";

Output

Notebook, Pen, Eraser

array_search() returns the key of the first match, or false. The strict !== false check is essential, because the first match here is at key 0.

All Occurrences: array_diff()

<?php
$tags = ['php', 'spam', 'mysql', 'spam'];

$clean = array_values(array_diff($tags, ['spam']));

print_r($clean);

Output

Array
(
    [0] => php
    [1] => mysql
)

array_diff($array, $valuesToRemove) returns the elements of the first array whose values do not appear in the second. It keeps the original keys, so array_values() re-indexes the result. array_diff() compares values as strings ((string) $a === (string) $b).


Removing Specific Keys: array_diff_key()

To remove a list of keys — for example, sensitive fields before sending data to a browser:

<?php
$user = [
    'id' => 7,
    'name' => 'Asha',
    'password_hash' => '$2y$10$abcdefghijklmnopqrstuv',
    'api_token' => 'abc123',
];

$sensitive = ['password_hash', 'api_token'];

$publicUser = array_diff_key($user, array_flip($sensitive));

echo json_encode($publicUser) . "\n";

Output

{"id":7,"name":"Asha"}
  • array_flip() turns the list of field names into keys: ['password_hash' => 0, 'api_token' => 1].
  • array_diff_key() keeps only keys of $user that are not in that list.
  • The original $user is unchanged.

The opposite — keeping only listed keys — is array_intersect_key($user, array_flip(['id', 'name'])). An allow-list ("keep only these") is safer than a block-list ("remove these"), because new sensitive fields added later are excluded automatically.


Removing by Condition: array_filter()

array_filter() keeps elements for which a callback returns true, removing the rest:

<?php
$stock = ['Pen' => 10, 'Lamp' => 0, 'Bag' => 3, 'Mug' => 0];

$inStock = array_filter($stock, fn(int $quantity): bool => $quantity > 0);

print_r($inStock);

Output

Array
(
    [Pen] => 10
    [Bag] => 3
)

The Default Filter Trap

Without a callback, array_filter() removes every falsy value — including '0' and 0:

<?php
$answers = ['Asha', '', 'Bala', null, '0'];

var_export(array_values(array_filter($answers)));
echo "\n";
var_export(array_values(array_filter($answers, fn($v) => $v !== '' && $v !== null)));
echo "\n";

Output

array (
  0 => 'Asha',
  1 => 'Bala',
)
array (
  0 => 'Asha',
  1 => 'Bala',
  2 => '0',
)

The default version silently drops the valid answer '0'. Pass an explicit callback whenever 0 or '0' can be legitimate data.


Removing Duplicates: array_unique()

<?php
$ratings = [3, 1, 3, 2, 1];

print_r(array_unique($ratings));
print_r(array_values(array_unique($ratings)));

Output

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

array_unique() keeps the first occurrence of each value and preserves its key. Re-index with array_values() for a clean list.


Removing Elements While Looping

Calling unset() on the array inside a foreach loop is safe — foreach iterates over the original list of elements:

<?php
$stock = ['Pen' => 10, 'Lamp' => 0, 'Bag' => 3, 'Mug' => 0];

foreach ($stock as $item => $quantity) {
    if ($quantity === 0) {
        unset($stock[$item]);
    }
}

echo implode(', ', array_keys($stock)) . "\n";

Output

Pen, Bag

array_filter() expresses the same thing more directly when you only need the remaining items.


Removing Everything

$cart = [];          // the variable still exists, as an empty array
unset($cart);        // the variable itself no longer exists

Use $cart = []; to empty an array you will keep using. Use unset($cart) only when the variable is no longer needed.


Practical Example: Removing Expired Coupons

<?php
$coupons = [
    'WELCOME10' => '2026-12-31',
    'DIWALI25' => '2026-10-20',
    'SUMMER15' => '2026-06-30',
    'FLASH50' => '2026-10-08',
];

$today = '2026-10-09';

$active = array_filter($coupons, fn(string $expiry): bool => $expiry >= $today);
$expired = array_diff_key($coupons, $active);

echo "Active:\n";
foreach ($active as $code => $expiry) {
    echo "  $code (valid until $expiry)\n";
}

echo "Removed: " . implode(', ', array_keys($expired)) . "\n";

Output

Active:
  WELCOME10 (valid until 2026-12-31)
  DIWALI25 (valid until 2026-10-20)
Removed: SUMMER15, FLASH50

Step-by-Step Explanation

  1. array_filter() keeps coupons whose expiry date is today or later. Dates in YYYY-MM-DD format compare correctly as strings because they are ordered from the largest unit (year) to the smallest (day). For other formats, compare DateTimeImmutable objects.
  2. array_diff_key() finds the coupons that were removed, by comparing keys of the original and the filtered array.
  3. Both results keep the coupon codes as keys, so the codes can be listed with array_keys().

In a real application, $today would be date('Y-m-d'), and expired coupons would usually be filtered in the database query (WHERE expires_on >= CURDATE()).


Common Mistakes

Expecting unset() to Re-index

Effect: Gaps break for loops and turn JSON arrays into objects.

Fix: Use array_values() afterwards, or array_splice().

Checking array_search() Loosely

Effect: A match at key 0 is treated as "not found".

Fix: if ($key !== false).

Default array_filter() Removing Valid Zeros

Effect: '0' and 0 disappear.

Fix: Always pass an explicit callback for user data.

Using array_splice() Offsets as Keys

Effect: In arrays with gaps or string keys, the wrong element is removed.

Fix: Use unset() for keys and array_splice() only for positions in lists.

Block-listing Sensitive Fields

Effect: New sensitive fields added later are exposed.

Fix: Allow-list public fields with array_intersect_key().


Best Practices

  • Use unset() to remove known keys, and array_values() to re-index lists afterwards.
  • Use array_splice(), array_pop(), and array_shift() for position-based removal in lists.
  • Use array_filter() with an explicit callback to remove by condition.
  • Use array_diff() / array_diff_key() to remove values or keys in bulk without modifying the original.
  • Prefer allow-lists over block-lists when removing fields for security.

Official reference: https://www.php.net/manual/en/function.unset.php

0 Comments

Reviewed before they appear

No comments yet.

PHP
PHP Home PHP Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope Static Variables Variable Variables PHP Echo / Print PHP printf / sprintf PHP Data Types PHP Booleans PHP NULL PHP Strings String Functions Modify Strings Concatenate Strings Slicing Strings Escape Characters String Interpolation Heredoc and Nowdoc Search in Strings Multibyte Strings PHP Floats PHP Casting PHP Type Juggling PHP Math PHP Random Numbers PHP Constants PHP Magic Constants PHP Operators Arithmetic Operators Assignment Operators Comparison Operators Increment / Decrement Operators Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence PHP If...Else...Elseif PHP If PHP If Operators PHP If...Else PHP Shorthand if PHP Nested if PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement Continue Statement PHP Functions User-defined Functions Function Arguments Default Argument Values Pass by Reference Named Arguments Variadic Functions Return Values Type Declarations in Functions Recursive Functions Variable Functions Anonymous Functions Closures Arrow Functions First-class Callable Syntax PHP Arrays Indexed Arrays Associative Arrays Create Arrays Access Array Items Update Array Items Add Array Items Remove Array Items Sorting Arrays Multidimensional Arrays Array Destructuring Array Spread Operator Search in Arrays Merge Arrays array_map / array_filter / array_reduce Array Functions PHP Superglobals $GLOBALS $_SERVER $_REQUEST $_POST $_GET $_FILES $_COOKIE $_SESSION \$\_ENV PHP RegEx RegEx Patterns RegEx Modifiers preg_match preg_replace preg_split PHP RegEx Functions PHP Form Handling PHP Form Validation PHP Form Required PHP Form URL/E-mail Form Input Sanitizing Escaping Output (htmlspecialchars) Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting DateTime Class Timezones PHP Include Include vs Require PHP File Handling PHP File Open/Read PHP File Create/Write File Delete / Rename / Copy PHP Directories PHP CSV Files PHP File Upload PHP Cookies PHP Sessions PHP Filters PHP Filters Advanced PHP Callback Functions PHP JSON PHP Exceptions Error Handling Custom Error Handler Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators PHP What is OOP PHP Classes/Objects The $this Keyword PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Destructor PHP Access Modifiers Readonly Properties PHP Inheritance Method Overriding The final Keyword PHP Class Constants PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning Comparing Objects Anonymous Classes PHP Enums PHP Namespaces Autoloading Classes PHP Iterables Iterators Object Serialization Strict Types Union Types Nullable Types Mixed and Never Types Nullsafe Operator PHP Attributes PHP Fibers Readonly Classes Property Hooks (PHP 8.4) Asymmetric Visibility (PHP 8.4) Reflection API SPL Data Structures MySQL Database MySQL Connect MySQL Create DB MySQL Create Table MySQL Insert Data MySQL Get Last ID MySQL Insert Multiple MySQL Prepared MySQL Select Data MySQL Where MySQL Order By MySQL Delete Data MySQL Update Data MySQL Limit Data MySQL Joins with PHP Pagination with PHP PDO Introduction PDO Connect PDO Prepared Statements PDO Fetch Modes PDO Transactions PDO Error Handling PHP XML Parsers PHP SimpleXML Parser PHP SimpleXML - Get PHP XML Expat Parser PHP DOM Parser PHP XMLReader PHP XMLWriter AJAX Intro AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention CSRF Protection Session Security Secure Cookies File Upload Security Filesystem Security Error Reporting in Production Hiding PHP Encryption with Sodium PHP Configuration (php.ini) PHP Command Line (CLI) Composer PSR-4 Autoloading Installing Extensions (PECL / PIE) Debugging PHP OPcache & Performance Garbage Collection PHP-FPM Migrating to PHP 8 Project: Contact Form with Email Project: Login & Registration System Project: CRUD App with MySQL Project: Image Upload Gallery Project: Shopping Cart with Sessions Project: Simple Blog Project: REST API with PHP
Ask about this post
AI Ask about this post

Ask questions about Remove Array Items and get answers drawn from it.

Signed-in readers only.