Question
I have an array in PHP that contains some empty string values submitted by users. After running this code, $linksArray still contains the empty elements:
foreach ($linksArray as $link) {
if ($link == '') {
unset($link);
}
}
print_r($linksArray);
Why are the empty values still present in the array, and what is the correct way to remove empty string elements from the array? I also tried using empty(), but that did not solve the problem.
Short Answer
By the end of this page, you will understand why unset($link) does not remove items from the original array during foreach in PHP, and how to correctly remove empty string values. You will also learn when to use unset() with keys, when array_filter() is a better choice, and how to safely clean user input arrays in real projects.
Concept
In PHP, a foreach loop gives you each array value one at a time. In this code:
foreach ($linksArray as $link)
$link is just a temporary variable holding the current value. It is not the actual array element itself. So when you call:
unset($link);
PHP only removes the temporary loop variable, not the item inside $linksArray.
To remove an item from the original array, you need access to its key and then unset that key:
foreach ($linksArray as $key => $link) {
if ($link === '') {
unset($linksArray[$key]);
}
}
This matters because cleaning arrays is very common in programming:
- processing form input
- removing blank fields
- validating API request data
- preparing database values
- sanitizing configuration arrays
There is also an important difference between checking for an and checking for a value PHP considers .
Mental Model
Think of foreach like handing you a copy of a note from a list.
$linksArrayis the full list on the wall.$linkis the note currently handed to you.unset($link)throws away the note in your hand.- The original note on the wall is still there.
If you want to remove the real item from the list, you must know its position and erase it from the list itself:
$keytells you where the item isunset($linksArray[$key])removes it from the real array
So the key idea is:
- unsetting the loop variable does not modify the source array
- unsetting the array element by key does
Syntax and Examples
Remove empty strings with foreach and unset
foreach ($linksArray as $key => $link) {
if ($link === '') {
unset($linksArray[$key]);
}
}
Why this works
$keyis the array index$linkis the current valueunset($linksArray[$key])removes the real element from the array
Example
$linksArray = ['google.com', '', 'example.com', ''];
foreach ($linksArray as $key => $link) {
if ($link === '') {
unset($linksArray[]);
}
}
();
Step by Step Execution
Trace example
$linksArray = ['A', '', 'B'];
foreach ($linksArray as $key => $link) {
if ($link === '') {
unset($linksArray[$key]);
}
}
print_r($linksArray);
Step by step
1. Initial array
['A', '', 'B']
Keys are:
0 => 'A'1 => ''2 => 'B'
2. First loop iteration
$keyis0$linkis'A'
Real World Use Cases
Removing empty array elements is common when working with user-provided data.
Form submissions
A form may allow users to enter multiple links, tags, or phone numbers. Some fields may be left blank:
$links = ['https://a.com', '', 'https://b.com'];
Before saving them, you remove empty values.
API request cleanup
An API may receive optional fields as empty strings. You often filter those out before validation or storage.
Search filters
A search form may submit some filters as blank values. Removing empty entries makes the query-building logic simpler.
CSV or imported data
When reading rows from files, some columns may contain empty strings. Filtering helps normalize the data.
Settings and configuration arrays
A config array may contain optional values that should be ignored if blank.
Real Codebase Usage
In real projects, developers usually do more than just remove empty strings. They often combine filtering with trimming, validation, and reindexing.
Common pattern: trim first, then filter
$linksArray = array_map('trim', $linksArray);
$linksArray = array_filter($linksArray, function ($link) {
return $link !== '';
});
$linksArray = array_values($linksArray);
This is common when cleaning form input.
Validation before saving
Developers often clean the array first, then validate each remaining item:
$linksArray = array_values(array_filter(array_map('trim', $linksArray), function ($link) {
return $link !== '';
}));
foreach ($linksArray as $link) {
if (!filter_var(, FILTER_VALIDATE_URL)) {
}
}
Common Mistakes
1. Unsetting the loop variable instead of the array element
Broken code:
foreach ($linksArray as $link) {
if ($link === '') {
unset($link);
}
}
Problem
This removes only the local variable $link, not the element in $linksArray.
Fix
foreach ($linksArray as $key => $link) {
if ($link === '') {
unset($linksArray[$key]);
}
}
2. Using empty() when '0' should be kept
Broken code:
$values = ['0', '', ];
= (, function () {
!();
});
Comparisons
| Approach | Best for | Removes only empty strings? | Keeps keys? | Notes |
|---|---|---|---|---|
foreach + unset($array[$key]) | When you want explicit control | Yes, if you check with === '' | Yes | Good for custom logic |
array_filter($array, fn($v) => $v !== '') | Simple cleanup | Yes | Yes | Short and readable |
array_filter($array) | Removing all falsey values | No | Yes | Also removes 0, '0', , |
Cheat Sheet
Remove empty strings from an array
Using foreach
foreach ($arr as $key => $value) {
if ($value === '') {
unset($arr[$key]);
}
}
Using array_filter
$arr = array_filter($arr, fn($value) => $value !== '');
Remove whitespace-only strings too
$arr = array_filter($arr, fn($value) => trim($value) !== '');
Reindex array after removing items
$arr = array_values();
FAQ
Why does unset($link) not remove the item from the array in PHP?
Because $link is just the loop variable holding the current value. It is not the original array element. You must unset the item by key, such as unset($linksArray[$key]).
How do I remove empty strings from an array in PHP?
Use either:
foreach ($array as $key => $value) {
if ($value === '') {
unset($array[$key]);
}
}
or:
$array = array_filter($array, fn($value) => $value !== '');
Why does empty() remove values like '0'?
In PHP, empty() treats several values as empty, including '', '0', , , , and . That is why it can be too broad for this task.
Mini Project
Description
Build a small PHP input-cleaning script for a list of user-submitted links. The script should remove blank entries, ignore entries that contain only spaces, and return a clean array ready for later validation or saving. This mirrors real form processing in web applications.
Goal
Create a PHP script that cleans an array of user-entered links by trimming values, removing blank entries, and reindexing the final array.
Requirements
- Start with an array containing valid links, empty strings, and whitespace-only strings.
- Trim each value before checking whether it is blank.
- Remove only blank entries from the array.
- Reindex the array so the final keys are sequential.
- Print the cleaned array at the end.
Keep learning
Related questions
Choosing the Right MySQL Collation for PHP and UTF-8
Learn how MySQL character sets and collations work with PHP, and how to choose a practical UTF-8 setup for web applications.
Convert a PHP Object to an Associative Array
Learn how to convert a PHP object to an associative array, including quick methods, recursion, pitfalls, and practical examples.
Convert a Postman Request to cURL and PHP cURL
Learn how to convert a Postman POST request into a cURL command and use the same request in PHP cURL with headers and body.