Remove empty array elements

前端 未结 27 3410
半阙折子戏
半阙折子戏 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:51

    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

提交回复
热议问题