Remove empty array elements

前端 未结 27 3402
半阙折子戏
半阙折子戏 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-22 00:06

    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 !== "";')));
    
    0 讨论(0)
  • 2020-11-22 00:06
    foreach($linksArray as $key => $link) 
    { 
        if($link === '') 
        { 
            unset($linksArray[$key]); 
        } 
    } 
    print_r($linksArray); 
    
    0 讨论(0)
  • 2020-11-22 00:07
        $myarray = array_filter($myarray, 'strlen');  //removes null values but leaves "0"
        $myarray = array_filter($myarray);            //removes all null values
    
    0 讨论(0)
提交回复
热议问题