Removing Empty Elements from a PHP Array Using foreach and array_filter

This article explains two PHP techniques for removing empty or falsy elements from an array: a straightforward foreach loop that unsets unwanted values and the more efficient array_filter() function with optional callbacks and flags, including code examples and the resulting output.

php Courses
php Courses
php Courses
Removing Empty Elements from a PHP Array Using foreach and array_filter

Method 1: Using a loop (foreach example)

The basic syntax is:

foreach (array_expression as $value)
foreach (array_expression as $key => $value)

Example code that removes falsy values by unsetting them:

<?php
foreach($arr as $k => $v){
if(!$v)
unset($arr[$k]);
}
?>

This approach is easy for beginners but has higher time and memory complexity, so it is generally not recommended for large arrays.

Method 2: Using array_filter() function

Signature:

array_filter(array $array [, callable $callback [, int $flag = 0 ]]) : array

The function passes each array value to the optional callback; if the callback returns true, the value is kept, otherwise it is removed. The keys are preserved unless a flag changes this behavior.

Key parameters: array: the array to be filtered. callback: optional function that determines whether a value should stay. If omitted, all entries equal to FALSE are removed. flag: determines how the callback receives arguments. ARRAY_FILTER_USE_KEY passes only the key, ARRAY_FILTER_USE_BOTH passes both key and value.

Example code:

<?php
$arr = array(
0 => 'hello',
1 => false,
2 => -1,
3 => null,
4 => ''
);
echo "<pre>";
var_dump(array_filter($arr));
?>

Running the script produces:

/*   array(2) {
[0]=> string(5) "hello"
[2]=> int(-1)
} */
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendPHPTutorialforeacharray_filter
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.