Remove empty array elements

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

    You can use array_filter to remove empty elements:

    $emptyRemoved = array_filter($linksArray);
    

    If you have (int) 0 in your array, you may use the following:

    $emptyRemoved = remove_empty($linksArray);
    
    function remove_empty($array) {
      return array_filter($array, '_remove_empty_internal');
    }
    
    function _remove_empty_internal($value) {
      return !empty($value) || $value === 0;
    }
    

    EDIT: Maybe your elements are not empty per se but contain one or more spaces... You can use the following before using array_filter

    $trimmedArray = array_map('trim', $linksArray);
    

提交回复
热议问题