Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Remove empty array elements

A few elements in my array are blank strings dependent on what the user has submitted. I need to eliminate those elements. I have this:

foreach($linksArray as $link)
{
if($link == '')
{
unset($link);
}
}
print_r($linksArray);


Yet, it doesn't work. $linksArray actually has blank elements. I have additionally taken a stab at doing it with the empty() function, however the result is something very similar.
by

3 Answers

akshay1995
As you're dealing with an array of strings, you can simply use array_filter(), which conveniently handles all this for you:

print_r(array_filter($linksArray));

Keep in mind that if no callback is supplied, all entries of array equal to FALSE (see converting to boolean) will be removed. So if you need to preserve elements that are i.e. exact string '0', you will need a custom callback:

// PHP 7.4 and later
print_r(array_filter($linksArray, fn($value) => !is_null($value) && $value !== ''));

// PHP 5.3 and later
print_r(array_filter($linksArray, function($value) { return !is_null($value) && $value !== ''; }));

// PHP < 5.3
print_r(array_filter($linksArray, create_function('$value', 'return $value !== "";')));
sandhya6gczb
If you want to remove empty elements use array_filter

$emptyRemoved = array_filter($linksArray);

if you want int 0 in your array,use this

$emptyRemoved = remove_empty($linksArray);

function remove_empty($array) {
return array_filter($array, '_remove_empty_internal');
}

function _remove_empty_internal($value) {
return !empty($value) || $value === 0;
}
RoliMishra
Consider the following PHP script:

<?php
$arr = array('1', '', '2', '3', '0');
// Incorrect:
print_r(array_filter($arr));
// Correct:
print_r(array_filter($arr, 'strlen'));

Login / Signup to Answer the Question.