1

This is Actually the original Array

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

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

And i want to remove the empty keys of this array 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 array_values `

but there is no use iam getting the same output i want the output has

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

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

please help me with this how i can achieve it

sai krishna
  • 105
  • 1
  • 9

2 Answers2

1

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
        )

)
Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106
0

Your coding attempt indicates that you wish to remove all emptyish, falsey, zero-like values using array_filter()'s default behavior on each subarray, then reindex the subarrays, then remove any first level arrays with no children by calling array_filter() again.

When functional programming offers a concise approach, it employs iterated function calls inside of the closure, and will therefore be more expensive than using language constructs to iterate.

The following provides the same functionality without any function calls and never needs to re-index the subarrays because the retained values are indexed as they as pushed into the result array.

Code: (Demo)

$array = [
    'radios1' => [
        'on',
    ],
    'empty' => [
        '',
        false,
    ],
    'from' => [
        '',
        'Bangalore',
        null,
        0,
    ]
];

$result = [];
foreach ($array as $key => $items) {
    foreach ($items as $item) {
        if ($item) {
            $result[$key][] = $item;
        }
    }
}

var_export($result);

Output:

array (
  'radios1' => 
  array (
    0 => 'on',
  ),
  'from' => 
  array (
    0 => 'Bangalore',
  ),
)

For anyone who wants to remove empty spaces and nulls, but retains zeros (integer or string typed), then use strlen($item) in the condition.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136