Remove empty array elements

2018-12-31 04:06发布

Some elements in my array are empty strings based on what the user has submitted. I need to remove those elements. I have this:

foreach($linksArray as $link)
{
    if($link == '')
    {
        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.

25条回答
不流泪的眼
2楼-- · 2018-12-31 04:46
function trim_array($Array)
{
    foreach ($Array as $value) {
        if(trim($value) === '') {
            $index = array_search($value, $Array);
            unset($Array[$index]);
        }
    }
    return $Array;
}
查看更多
旧人旧事旧时光
3楼-- · 2018-12-31 04:47
foreach($linksArray as $key => $link) 
{ 
    if($link === '') 
    { 
        unset($linksArray[$key]); 
    } 
} 
print_r($linksArray); 
查看更多
姐姐魅力值爆表
4楼-- · 2018-12-31 04:47

I had to do this in order to keep an array value of (string) 0

$url = array_filter($data, function ($value) {
  return (!empty($value) || $value === 0 || $value==='0');
});
查看更多
闭嘴吧你
5楼-- · 2018-12-31 04:50

In short:

This is my suggested code:

$myarray =  array_values(array_filter(array_map('trim', $myarray), 'strlen'));

Explanation:

I thinks use array_filter is good, but not enough, because values be like space and \n,... keep in the array and this is usually bad.

So I suggest you use mixture ‍‍array_filter and array_map.

array_map is for trimming, array_filter is for remove empty values, strlen is for keep 0 value, and array_values is for re indexing if you needed.

Samples:

$myarray = array("\r", "\n", "\r\n", "", " ", "0", "a");

// "\r", "\n", "\r\n", " ", "a"
$new1 = array_filter($myarray);

// "a"
$new2 = array_filter(array_map('trim', $myarray));

// "0", "a"
$new3 = array_filter(array_map('trim', $myarray), 'strlen');

// "0", "a" (reindex)
$new4 = array_values(array_filter(array_map('trim', $myarray), 'strlen'));

var_dump($new1, $new2, $new3, $new4);

Results:

array(5) {
  [0]=>
" string(1) "
  [1]=>
  string(1) "
"
  [2]=>
  string(2) "
"
  [4]=>
  string(1) " "
  [6]=>
  string(1) "a"
}
array(1) {
  [6]=>
  string(1) "a"
}
array(2) {
  [5]=>
  string(1) "0"
  [6]=>
  string(1) "a"
}
array(2) {
  [0]=>
  string(1) "0"
  [1]=>
  string(1) "a"
}

Online Test:

http://phpio.net/s/5yg0

查看更多
萌妹纸的霸气范
6楼-- · 2018-12-31 04:50

The most voted answer is wrong or at least not completely true as the OP is talking about blank strings only. Here's a thorough explanation:

What does empty mean?

First of all, we must agree on what empty means. Do you mean to filter out:

  1. the empty strings only ("")?
  2. the strictly false values? ($element === false)
  3. the falsey values? (i.e. 0, 0.0, "", "0", NULL, array()...)
  4. the equivalent of PHP's empty() function?

How do you filter out the values

To filter out empty strings only:

$filtered = array_diff($originalArray, array(""));

To only filter out strictly false values, you must use a callback function:

$filtered = array_diff($originalArray, 'myCallback');
function myCallback($var) {
    return $var === false;
}

The callback is also useful for any combination in which you want to filter out the "falsey" values, except some. (For example, filter every null and false, etc, leaving only 0):

$filtered = array_filter($originalArray, 'myCallback');
function myCallback($var) {
    return ($var === 0 || $var === '0');
}

Third and fourth case are (for our purposes at last) equivalent, and for that all you have to use is the default:

$filtered = array_filter($originalArray);
查看更多
回忆,回不去的记忆
7楼-- · 2018-12-31 04:51

Remove empty array elements

function removeEmptyElements(&$element)
{
    if (is_array($element)) {
        if ($key = key($element)) {
            $element[$key] = array_filter($element);
        }

        if (count($element) != count($element, COUNT_RECURSIVE)) {
            $element = array_filter(current($element), __FUNCTION__);
        }

        return $element;
    } else {
        return empty($element) ? false : $element;
    }
}

$data = array(
    'horarios' => array(),
    'grupos' => array(
        '1A' => array(
            'Juan' => array(
                'calificaciones' => array(
                    'Matematicas' => 8,
                    'Español' => 5,
                    'Ingles' => 9,
                ),
                'asistencias' => array(
                    'enero' => 20,
                    'febrero' => 10,
                    'marzo' => '',
                )
            ),
            'Damian' => array(
                'calificaciones' => array(
                    'Matematicas' => 10,
                    'Español' => '',
                    'Ingles' => 9,
                ),
                'asistencias' => array(
                    'enero' => 20,
                    'febrero' => '',
                    'marzo' => 5,
                )
            ),
        ),
        '1B' => array(
            'Mariana' => array(
                'calificaciones' => array(
                    'Matematicas' => null,
                    'Español' => 7,
                    'Ingles' => 9,
                ),
                'asistencias' => array(
                    'enero' => null,
                    'febrero' => 5,
                    'marzo' => 5,
                )
            ),
        ),
    )
);

$data = array_filter($data, 'removeEmptyElements');
var_dump($data);

¡it works!

查看更多
登录 后发表回答