phparraysmultidimensional-arrayfilteringreindex

Filter and reindex all rows of a 2d array


This is the original array:

[radios1] => Array
    (
        [0] => on
    )

[from] => Array
    (
        [0] => 
        [1] => Bangalore
        [2] => 
        [3] => 
    )

And I want to remove the empty elements of each row so I used this code to do so:

$array = array_map('array_filter', $_POST);
$array = array_filter($array);

And the output of this is as follows

[radios1] => Array
    (
        [0] => on
    )

[from] => Array
    (
        [1] => Bangalore
    )

Here I have been able to remove the keys with empty values but the filtered keys should be reindexed. I have used both array_merge() and array_values(), but there is no use. I am getting the same output; I want the output as:

[radios1] => Array
    (
        [0] => on
    )

[from] => Array
    (
        [0] => Bangalore
    )

Solution

  • I would use array_walk and then array_filter then array_values to reset the index.

    For example:

    <?php
    $array = [
        'radios1' => [
            'on'
        ],
        'from' => [
            '',
            'Bangalore',
            '',
            '',
        ]
    ];
    
    array_walk($array, function (&$value, $key) {
        $value = array_values(array_filter($value));
    });
    
    print_r($array);
    

    https://3v4l.org/Km1i8

    Result:

    Array
    (
        [radios1] => Array
            (
                [0] => on
            )
    
        [from] => Array
            (
                [0] => Bangalore
            )
    
    )