Remove empty array elements

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

    I think array_walk is much more suitable here

    $linksArray = array('name', '        ', '  342', '0', 0.0, null, '', false);
    
    array_walk($linksArray, function(&$v, $k) use (&$linksArray){
        $v = trim($v);
        if ($v == '')
            unset($linksArray[$k]);
    });
    print_r($linksArray);
    

    Output:

    Array
    (
        [0] => name
        [2] => 342
        [3] => 0
        [4] => 0
    )
    
    • We made sure that empty values are removed even if the user adds more than one space

    • We also trimmed empty spaces from the valid values

    • Finally, only (null), (Boolean False) and ('') will be considered empty strings

    As for False it's ok to remove it, because AFAIK the user can't submit boolean values.

提交回复
热议问题