Remove empty array elements

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

    With these types of things, it's much better to be explicit about what you want and do not want.

    It will help the next guy to not get caught by surprise at the behaviour of array_filter() without a callback. For example, I ended up on this question because I forgot if array_filter() removes NULL or not. I wasted time when I could have just used the solution below and had my answer.

    Also, the logic is language angnostic in the sense that the code can be copied into another language without having to under stand the behaviour of a php function like array_filter when no callback is passed.

    In my solution, it is clear at glance as to what is happening. Remove a conditional to keep something or add a new condition to filter additional values.

    Disregard the actual use of array_filter() since I am just passing it a custom callback - you could go ahead and extract that out to its own function if you wanted. I am just using it as sugar for a foreach loop.

    ";
    var_export($xs);
    

    Another benefit of this approach is that you can break apart the filtering predicates into an abstract function that filters a single value per array and build up to a composable solution.

    See this example and the inline comments for the output.

     [0, 1, 2, 3, false, "0", ""]
    $xs = $filterFalse($xs);       //=> [0, 1, 2, 3, "0", ""]
    $xs = $filterZeroString($xs);  //=> [0, 1, 2, 3, ""]
    $xs = $filterEmptyString($xs); //=> [0, 1, 2, 3]
    
    echo "
    ";
    var_export($xs); //=> [0, 1, 2, 3]
    

    Now you can dynamically create a function called filterer() using pipe() that will apply these partially applied functions for you.

    ";
    var_export($xs); //=> [0, 1, 2, 3]
    

提交回复
热议问题