Remove empty array elements

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

    The most popular answer on this topic is absolutely INCORRECT.

    Consider the following PHP script:

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

提交回复
热议问题