Current array:
Array (
[name] => Array (
[name1] => Array (
[0] => some value1
)
[name2] => Array (
[0] => some value2
)
[name3] => Array (
[0] =>
)
)
Wanted array:
Array (
[name] => Array (
[name1] => Array (
[0] => some value1
)
[name2] => Array (
[0] => some value2
)
)
Since name3[0]
doesn't contain any value, it needs to be removed.
From what I read, I should use array_filter
for this, but I can't get it to work.
In order to remove empty elements from an array, filter() method is used. This method will return a new array with the elements that pass the condition of the callback function.
You can use the PHP array_unique() function and PHP array_merge() function together to merge two arrays into one array without duplicate values in PHP.
Basic example of empty array:$emptyArray = ( array ) null; var_dump( $emptyArray );
The array_unique() function removes duplicate values from an array. If two or more array values are the same, the first appearance will be kept and the other will be removed. Note: The returned array will keep the first array item's key type.
Recursive function, it will remove all empty values and empty arrays from input array:
//clean all empty values from array
function cleanArray($array)
{
if (is_array($array))
{
foreach ($array as $key => $sub_array)
{
$result = cleanArray($sub_array);
if ($result === false)
{
unset($array[$key]);
}
else
{
$array[$key] = $result;
}
}
}
if (empty($array))
{
return false;
}
return $array;
}
I have tested it on this example, it works no matter how deep is array:
$array = array(
'name' => array(
'name1' => array(0 => 1),
'name2' => array(0 => 3, 1 => array(5 => 0, 1 => 5)),
'name3' => array(0 => '')
)
);
Hope this helps :)
You need to feed array_filter
a predicate (function) that determines if the [0]
sub-element of each array element is empty or not. So:
$array = array_filter($array, function($item) { return !empty($item[0]); });
Be aware that empty
is not very picky: it will result in removing any item whose [0]
sub-element is the empty string, false
, null
, 0
or "0"
-- it will also remove items that do not have a [0]
sub-element at all. If you need something more surgically targeted the test needs to be fine-tuned.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With