Remove empty array elements

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

    You can just do

    array_filter($array)
    

    array_filter: "If no callback is supplied, all entries of input equal to FALSE will be removed." This means that elements with values NULL, 0, '0', '', FALSE, array() will be removed too.

    The other option is doing

    array_diff($array, array(''))
    

    which will remove elements with values NULL, '' and FALSE.

    Hope this helps :)

    UPDATE

    Here is an example.

    $a = array(0, '0', NULL, FALSE, '', array());
    
    var_dump(array_filter($a));
    // array()
    
    var_dump(array_diff($a, array(0))) // 0 / '0'
    // array(NULL, FALSE, '', array());
    
    var_dump(array_diff($a, array(NULL))) // NULL / FALSE / ''
    // array(0, '0', array())
    

    To sum up:

    • 0 or '0' will remove 0 and '0'
    • NULL, FALSE or '' will remove NULL, FALSE and ''

提交回复
热议问题