Remove empty array elements

前端 未结 27 3401
半阙折子戏
半阙折子戏 2020-11-21 23:17

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)         


        
相关标签:
27条回答
  • 2020-11-21 23:52

    You can just do

    array_filter($array)
    

    array_filter: "If no callback is supplied, all entries of input equal to FALSE will be removed." This means that elements with values NULL, 0, '0', '', FALSE, array() will be removed too.

    The other option is doing

    array_diff($array, array(''))
    

    which will remove elements with values NULL, '' and FALSE.

    Hope this helps :)

    UPDATE

    Here is an example.

    $a = array(0, '0', NULL, FALSE, '', array());
    
    var_dump(array_filter($a));
    // array()
    
    var_dump(array_diff($a, array(0))) // 0 / '0'
    // array(NULL, FALSE, '', array());
    
    var_dump(array_diff($a, array(NULL))) // NULL / FALSE / ''
    // array(0, '0', array())
    

    To sum up:

    • 0 or '0' will remove 0 and '0'
    • NULL, FALSE or '' will remove NULL, FALSE and ''
    0 讨论(0)
  • 2020-11-21 23:54

    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');
    });
    
    0 讨论(0)
  • 2020-11-21 23:54

    Just one line : Update (thanks to @suther):

    $array_without_empty_values = array_filter($array);
    
    0 讨论(0)
  • 2020-11-21 23:55

    use array_filter function to remove empty values:

    $linksArray = array_filter($linksArray);
    print_r($linksArray);
    
    0 讨论(0)
  • 2020-11-21 23:56

    The most popular answer on this topic is absolutely INCORRECT.

    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'));
    

    Why is this? Because a string containing a single '0' character also evaluates to boolean false, so even though it's not an empty string, it will still get filtered. That would be a bug.

    Passing the built-in strlen function as the filtering function will work, because it returns a non-zero integer for a non-empty string, and a zero integer for an empty string. Non-zero integers always evaluate to true when converted to boolean, while zero integers always evaluate to false when converted to boolean.

    So, the absolute, definitive, correct answer is:

    $arr = array_filter($arr, 'strlen');
    
    0 讨论(0)
  • 2020-11-21 23:56

    For multidimensional array

    $data = array_map('array_filter', $data);
    $data = array_filter($data);
    
    0 讨论(0)
提交回复
热议问题