views:

32

answers:

4

Some elements in my array are empty based on what the user has entered. I need to remove these elements. This is my code to do so:

// Remove empty elements
foreach($linksArray as $link)
{
    if($links == '')
    {
        unset($link);
    }
}
print_r($linksArray);

But it doesn't work, $linksArray still has empty elements. I have also tried doing it with the empty() function but the outcome is the same.

Any help is appreciated, thanks.

A: 
foreach($linksArray as $key => $link) 
{ 
    if($link == '') 
    { 
        unset($linksArray[$key]); 
    } 
} 
print_r($linksArray); 
Mark Baker
+1  A: 

You have a typo in your if condition, it should be $link not $links.

As for the loop itself, you can try unsetting by keys instead:

foreach ($linksArray as $key => $link)
{
    if ($linksArray[$key] == '')
    {
        unset($linksArray[$key]);
    }
}

Or using a reference (PHP 5 only):

foreach ($linksArray as &$link)
{
    if ($link == '')
    {
        unset($link);
    }
}
BoltClock
That was a typo haha, sorry. It's correct in my real code. Thanks for the answer :)
Will
A: 
$linksArray = array_filter($linksArray);

"If no callback is supplied, all entries of input equal to FALSE will be removed." -- http://php.net/manual/en/function.array-filter.php

Yorirou
I also tried this after Google'ing the problem. Unfortunately, it leaves in the blank elements for me.
Will
this will also remove '0'
OIS
A: 

You can use array_filter to remove empty elements:

$emptyRemoved = array_filter($linksArray);

If you have (int) 0 in your array, you may use the following:

$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;
}

EDIT: Maybe your elements are not empty per say but contain one or more spaces... You can use the following before using array_filter

$trimmedArray = array_map('trim', $linksArray);
Andrew Moore