Search code examples
phparraysforeachunset

Remove multiple values from array


I have the following array:

array(5) { 
    ["destino"]=> string(11) "op_list_gen" 
    ["id_terminal"]=> string(0) "" 
    ["marca"]=> string(2) "--" 
    ["tipo"]=> string(2) "--" 
    ["lyr_content"]=> string(14) "aawaw"
}

How can I remove the values "--" and empty values from the array?

I have tried using a foreach and removing the elements found with unset but it´s not working.

foreach ($array as $key => $arra) {
        if(array_key_exists('--', $array)){ 
            unset($arra[$key]);
        }
}

Solution

  • You can use array_filter to solve this:

    $arr = [
        "destino" => "op_list_gen",
        "id_terminal" => "",
        "marca" => "--",
        "tipo" => "--",
        "lyr_content" => "aawaw"
    ];
    
    $newArr = array_filter($arr, function($value) {
        return !in_array($value, ['', '--']);
    });
    

    demo: https://ideone.com/oot7lZ