phparraysfilterconditional-statementsmerging-data

Merge two flat arrays into a new flat array with no empty values


I have two input arrays.

$cad_cons => ['', '200', '500', ''];

$man_cons => ['228.44', '', '', '320.04'];

I need to merge them like this:

$cons = ['228.44', '200', '500', '320.04'];

Are there any PHP functions for this operation?


Solution

  • All you need is a combination of array_filter() and array_merge().

    $a = ['', '200', '500', ''];
    $b = ['228.44', '', '', '320.04'];
    
    $a = array_filter($a); 
    $b = array_filter($b);
    
    print_r(array_merge($a, $b));
    

    The above will give you.

    Array
    (
        [0] => 200
        [1] => 500
        [2] => 228.44
        [3] => 320.04
    )