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
nullchanges its value tonull - 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.
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"
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:
-
PHP creates the array:
- key
0=>'a' - key
1=>'b' - key
2=>'c'
- key
-
unset($array[1])removes the entry with key1completely. -
The array now contains:
- key
0=>'a'
- key
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 when the setting should not exist at all.
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.
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:
Comparisons
| Approach | What it does | Removes key? | Keeps indexes? | Best use |
|---|---|---|---|---|
$array[1] = null; | Changes value to null | No | Yes | When the key should still exist but have no value |
unset($array[1]); | Removes key-value pair | Yes | Numeric gaps may remain | When deleting a specific element |
array_filter($array) | Removes elements based on a rule | Yes, in result | Original keys preserved | When cleaning many items by condition |
array_values($array) | Rebuilds numeric indexes |
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
nullmeans the key still exists with an empty valueunset()removes the key entirelyforeachloops 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
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. checks whether the key exists regardless of value.
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
foreachand print remaining tasks - Reindex the array with
array_values()before printing a second time
Keep learning
Related questions
Converting HTML and CSS to PDF in PHP: Core Concepts, Limits, and Practical Approaches
Learn how HTML-to-PDF conversion works in PHP, why CSS support varies, and how to choose practical approaches for reliable PDF output.
How PHP foreach Actually Works with Arrays
Learn how PHP foreach works internally, including array copies, internal pointers, by-value vs by-reference behavior, and common pitfalls.
How to Check String Prefixes and Suffixes in PHP
Learn how to check whether a string starts or ends with specific text in PHP using simple functions and practical examples.