Question

How to Delete an Element from an Array in PHP

phparraysunset

Question

In PHP, what is the correct way to remove an element from an array so that a foreach loop no longer includes it?

For example, I expected assigning null to an element to remove it, but that does not seem to work:

$array = ['a', 'b', 'c'];
$array[1] = null;

foreach ($array as $value) {
    echo $value;
}

Why does this still keep the array element, and what is the proper way to delete it?

Short Answer

By the end of this page, you will understand how PHP arrays store elements, why setting a value to null does not remove the array entry, and how to properly delete elements using unset(). You will also learn when to reindex an array, when to use array_filter(), and what common mistakes to avoid.

Concept

PHP arrays are associative data structures that map keys to values. Even when you use numeric indexes like 0, 1, and 2, PHP still treats the array as key-value storage.

That detail explains the core issue:

  • Setting an element to null changes its value to null
  • It does not remove the key from the array
  • So the element still exists and can still be visited by foreach

To actually delete an element from a PHP array, use unset():

unset($array[1]);

This removes the key-value pair entirely.

Why this matters in real programming:

  • You may need to remove invalid items from a list
  • You may want to skip deleted records in loops
  • You may need to clean user input before processing it
  • You may want arrays to reflect current state accurately

Understanding the difference between changing a value and removing an element is essential when working with collections in PHP.

Mental Model

Think of a PHP array like a set of labeled boxes on a shelf.

  • The key is the label on the box
  • The value is what is inside the box

If you set a box's contents to null, the box is still on the shelf with its label.

If you use unset(), you remove the whole box from the shelf.

A foreach loop walks past every box that still exists. It does not care whether the box contains null, a string, or a number. If the box is still there, foreach can include it.

Take Quiz

Syntax and Examples

Remove one element with unset()

$array = ['a', 'b', 'c'];
unset($array[1]);

foreach ($array as $value) {
    echo $value . PHP_EOL;
}

Output:

a
c

Here, the element at key 1 is removed completely.

Setting to null does not delete the element

$array = ['a', 'b', 'c'];
$array[1] = null;

foreach ($array as $value) {
    var_dump($value);
}

Output:

string(1) "a"
NULL
string(1) "c"

The key still exists, so foreach still visits it.

Reindexing after deletion

When you remove an item from a numerically indexed array, the indexes are not automatically reset.

$array = ['a', 'b', 'c'];
unset($array[1]);
print_r($array);

Output:

Array
(
    [0] => a
    [2] => c
)

If you want consecutive numeric indexes again, use array_values():

$array = array_values($array);
print_r($array);

Output:

Array
(
    [0] => a
    [1] => c
)

Remove multiple items with array_filter()

$array = ['apple', '', 'banana', null, 'orange'];
$clean = array_filter($array, fn($item) => $item !== '' && $item !== null);

print_r($clean);

This is useful when you want to keep only values matching a rule.

Step by Step Execution

Consider this example:

$array = ['a', 'b', 'c'];
unset($array[1]);

foreach ($array as $key => $value) {
    echo $key . ': ' . $value . PHP_EOL;
}

Step by step:

  1. PHP creates the array:

    • key 0 => 'a'
    • key 1 => 'b'
    • key 2 => 'c'
  2. unset($array[1]) removes the entry with key 1 completely.

  3. The array now contains:

    • key 0 => 'a'
    • key 2 => 'c'
  4. foreach loops over existing entries only.

  5. First iteration:

    • $key is 0
    • $value is 'a'
  6. Second iteration:

    • $key is 2
    • $value is 'c'

Output:

0: a
2: c

Notice that key 1 is gone, not replaced.

Real World Use Cases

Removing invalid form inputs

If a user submits a list of values, you may remove empty entries before saving them.

$tags = ['php', '', 'arrays', null];
$tags = array_filter($tags, fn($tag) => $tag !== '' && $tag !== null);

Deleting items from a shopping cart

unset($cart[$productId]);

This removes the product from the cart entirely.

Excluding failed records from batch processing

If a record fails validation, you may remove it before the next processing step.

unset($records[$index]);

Cleaning API response data

Sometimes an API returns placeholder or unwanted values. You can remove them before returning data to the frontend.

Managing configuration arrays

Applications often build configuration arrays dynamically. Removing a key with unset() is cleaner than assigning null when the setting should not exist at all.

Take Quiz

Real Codebase Usage

In real projects, developers often choose between several removal patterns depending on the goal.

1. Direct removal with unset()

Used when you know the exact key to remove.

if (isset($data['debug'])) {
    unset($data['debug']);
}

2. Guard clauses before removal

This avoids notices or makes intent clearer.

if (array_key_exists('temporary_token', $sessionData)) {
    unset($sessionData['temporary_token']);
}

3. Filtering arrays by rule

Useful when removing many elements based on validation.

$users = array_filter($users, fn($user) => $user['active'] === true);

4. Reindexing lists for output

After deleting from a list, developers often reindex before sending JSON or rendering a view.

$items = array_values($items);

5. Cleaning request payloads

unset($payload['csrf_token']);
unset($payload['submit_button']);

This is common before storing or transforming form data.

In short:

  • Use unset() when removing by key
  • Use array_filter() when removing by condition
  • Use array_values() if you need clean numeric indexes afterward

Common Mistakes

Mistake 1: Assuming null removes the element

Broken example:

$array = ['a', 'b', 'c'];
$array[1] = null;

This does not remove key 1. It only changes its value.

Correct version:

unset($array[1]);

Mistake 2: Expecting numeric indexes to reset automatically

$array = ['a', 'b', 'c'];
unset($array[1]);
print_r($array);

Result:

Array
(
    [0] => a
    [2] => c
)

If you need sequential indexes, do this:

$array = array_values($array);

Mistake 3: Using isset() when null is a valid value

isset($array['x']) returns false if the key exists but its value is null.

$array['x'] = null;
var_dump(isset($array['x'])); // false

If you need to know whether the key exists at all, use array_key_exists().

var_dump(array_key_exists('x', $array)); // true

Mistake 4: Removing elements while assuming loop order or indexes stay simple

If you delete items during processing, be careful with logic that depends on consecutive indexes.

Mistake 5: Using array_filter() without understanding preserved keys

array_filter() keeps original keys by default.

$array = ['a', '', 'c'];
$result = array_filter($array);
print_r($result);

The resulting indexes may have gaps. Use array_values() if needed.

Comparisons

ApproachWhat it doesRemoves key?Keeps indexes?Best use
$array[1] = null;Changes value to nullNoYesWhen the key should still exist but have no value
unset($array[1]);Removes key-value pairYesNumeric gaps may remainWhen deleting a specific element
array_filter($array)Removes elements based on a ruleYes, in resultOriginal keys preservedWhen cleaning many items by condition
array_values($array)Rebuilds numeric indexesNo deletion by itselfYes, resets numeric indexesAfter removal when you need 0,1,2...

unset() vs setting to null

  • Use unset() to delete
  • Use null to keep the entry but mark it as empty or unknown

unset() vs array_filter()

  • Use unset() for one known key
  • Use array_filter() for rule-based cleanup across many elements
Take Quiz

Cheat Sheet

// Remove one element by key
unset($array[$key]);

// Set value to null (does NOT remove element)
$array[$key] = null;

// Reindex numeric array after deletion
$array = array_values($array);

// Remove empty values by condition
$array = array_filter($array, fn($value) => $value !== null && $value !== '');

Key rules

  • PHP arrays are key-value maps
  • null means the key still exists with an empty value
  • unset() removes the key entirely
  • foreach loops over existing elements
  • After unset() on numeric arrays, indexes may have gaps
  • Use array_values() to reset numeric indexes
  • array_filter() preserves keys unless you reindex manually

Useful checks

isset($array['x']);           // false if key missing OR value is null
array_key_exists('x', $array); // true if key exists, even if value is null

FAQ

Why does foreach still include an element set to null in PHP?

Because the array key still exists. Only the value changed to null.

How do I completely remove an array element in PHP?

Use unset($array[$key]);.

Does unset() reset array indexes in PHP?

No. Numeric indexes are preserved, so gaps may remain.

How do I reset array indexes after deleting an element?

Use array_values($array).

Should I use unset() or array_filter()?

Use unset() to remove a known key. Use array_filter() to remove items based on a condition.

What is the difference between isset() and array_key_exists()?

isset() returns false for missing keys and for keys with null values. array_key_exists() checks whether the key exists regardless of value.

Can I remove elements from an associative array with unset()?

Yes. unset() works for both numeric and string keys.

Take Quiz

Mini Project

Description

Build a small PHP script that manages a to-do list stored in an array. You will remove completed tasks, display the remaining tasks, and optionally reindex the list for clean output. This demonstrates the difference between changing a value and truly removing an element.

Goal

Create a PHP program that deletes tasks from an array correctly and shows the remaining items in a foreach loop.

Requirements

  • Create an array with at least four task names
  • Remove one task using unset()
  • Loop through the array with foreach and print remaining tasks
  • Reindex the array with array_values() before printing a second time
Take Quiz

Keep learning

Related questions

View more