Reputation: 99
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
)
Upvotes: 1
Views: 163
Reputation: 48070
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.
Upvotes: 0
Reputation: 46650
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);
Result:
Array
(
[radios1] => Array
(
[0] => on
)
[from] => Array
(
[0] => Bangalore
)
)
Upvotes: 1