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 empty string and checking for a value PHP considers empty.
For example:
empty(''); // true
empty('0'); // true
If the string '0' is a valid value in your app, then empty() may remove too much. If you only want to remove blank strings, use a strict comparison like:
$link === ''
Or, if you want to remove blank strings that may contain only spaces:
trim($link) === ''
For many cases, array_filter() is the cleanest solution.
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[$key]);
}
}
print_r($linksArray);
Output:
Array
(
[0] => google.com
[2] => example.com
)
Notice that PHP keeps the original keys. If you want a clean zero-based index afterward, use array_values():
$linksArray = array_values($linksArray);
Remove empty strings with array_filter
$linksArray = array_filter($linksArray, function ($link) {
return $link !== '';
});
Example with reindexing
$linksArray = ['google.com', '', 'example.com', ''];
$linksArray = array_filter($linksArray, function ($link) {
return $link !== '';
});
$linksArray = array_values($linksArray);
print_r($linksArray);
Output:
Array
(
[0] => google.com
[1] => example.com
)
Remove blank strings including spaces
If users may submit values like ' ', trim them first:
$linksArray = array_filter($linksArray, function ($link) {
return trim($link) !== '';
});
Be careful with empty()
$value1 = '';
$value2 = '0';
var_dump(empty($value1)); // true
var_dump(empty($value2)); // true
If '0' is valid data, do not use empty() for this job.
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'- condition
$link === ''is false - nothing is removed
Array stays:
['A', '', 'B']
3. Second loop iteration
$keyis1$linkis''- condition
$link === ''is true unset($linksArray[1])removes that element
Array becomes:
[
0 => 'A',
2 => 'B'
]
4. Third loop iteration
$keyis2$linkis'B'- condition is false
- nothing changes
5. Final result
Array
(
[0] => A
[2] => B
)
6. Optional reindexing
$linksArray = array_values($linksArray);
Now the array becomes:
['A', 'B']
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($link, FILTER_VALIDATE_URL)) {
// handle invalid URL
}
}
Guard clause style
If the array is empty after filtering, code may stop early:
$linksArray = array_values(array_filter($linksArray, fn($link) => trim($link) !== ''));
if ($linksArray === []) {
return;
}
Normalizing incoming request data
In frameworks, developers often sanitize request arrays before business logic uses them. This reduces bugs later in the request flow.
Preserving intentional values
Experienced developers avoid empty() when values like 0, '0', or false are meaningful. They use strict checks to remove only what they truly want removed.
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', '', 'hello'];
$values = array_filter($values, function ($value) {
return !empty($value);
});
Problem
This removes both '' and '0'.
Fix
$values = array_filter($values, function ($value) {
return $value !== '';
});
3. Forgetting about whitespace-only strings
Broken code:
$values = ['hello', ' ', 'world'];
$values = array_filter($values, function ($value) {
return $value !== '';
});
Problem
' ' is not equal to '', so it stays in the array.
Fix
$values = array_filter($values, function ($value) {
return trim($value) !== '';
});
4. Forgetting that keys remain after unset()
$values = ['a', '', 'b'];
foreach ($values as $key => $value) {
if ($value === '') {
unset($values[$key]);
}
}
print_r($values);
Output:
Array
(
[0] => a
[2] => b
)
Fix if you need sequential indexes
$values = array_values($values);
5. Using loose comparison when strict comparison is clearer
Less clear:
if ($link == '')
Better:
if ($link === '')
Strict comparison helps avoid type-conversion surprises.
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', false, null |
empty($value) | Broad empty checks | No | N/A | Can be too aggressive |
trim($value) === '' | Removing blank or whitespace-only strings | Yes | N/A | Best for form input |
unset() vs array_filter()
Use unset() when
- you are already looping
- you need complex conditions
- you want to remove items during custom processing
Use array_filter() when
- you want a cleaner, more functional style
- the task is simply “keep valid items”
- readability matters more than manual control
== vs ===
| Operator | Meaning | Recommended here? |
|---|---|---|
== | Loose comparison | Usually no |
=== | Strict comparison | Yes |
For removing empty strings specifically, === '' is the safest and clearest choice.
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($arr);
Important rules
unset($value)insideforeachdoes not remove the original array item- use
$key => $valueif you need to delete from the array empty('')istrueempty('0')is alsotrue- use
=== ''if you only want to remove empty strings - use
trim($value) === ''if spaces should count as empty
Quick patterns
Keep only non-blank user input
$arr = array_values(array_filter(array_map('trim', $arr), fn($value) => $value !== ''));
Preserve keys
$arr = array_filter($arr, fn($value) => $value !== '');
Remove exact empty strings only
if ($value === '')
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', 0, false, null, and []. That is why it can be too broad for this task.
How do I remove values that contain only spaces?
Use trim():
$array = array_filter($array, fn($value) => trim($value) !== '');
Why are my array indexes missing after unset()?
unset() removes elements but does not automatically reindex numeric keys. Use array_values() if you want consecutive indexes.
Should I use foreach or array_filter()?
Use array_filter() for simple cleanup and readability. Use foreach if you need more complex logic while iterating.
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
Are PDO Prepared Statements Enough to Prevent SQL Injection in PHP?
Learn how PDO prepared statements prevent SQL injection in PHP, what they protect, and the mistakes that still leave MySQL apps vulnerable.
Can You Bind an Array to an IN Clause in PHP PDO?
Learn how PDO handles placeholders in IN() clauses, why arrays cannot be bound directly, and the safe PHP pattern to build dynamic queries.
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.