Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
array_filter_recursive
<?php
/**
* @param mixed $input
* @param null|callable $callback
* @return array
*/
function array_filter_recursive($input, $callback = null) {
if (!is_array($input)) {
return $input;
}
if (null === $callback) {
$callback = function ($v) { return !empty($v);};
}
$input = array_map(function($v) use ($callback) { return array_filter_recursive($v, $callback); }, $input);
return array_filter($input, $callback);
}
class FunctionsTest extends \PHPUnit_Framework_TestCase
{
public function testArrayFilterRecursive()
{
$array = [
'a'=> 'a',
'b'=> null,
'c' => [
'a' => null,
'b' => 'b',
],
'd' => [
'a' => null
]
];
$result = array_filter_recursive($array);
$expected = [
'a'=> 'a',
'c' => [
'b' => 'b',
],
];
$this->assertSame($expected, $result);
}
public function testArrayFilterRecursiveWithCustomCallback()
{
$array = [
'a'=> 'a',
'b'=> null,
'c' => [
'a' => null,
'b' => 'b',
],
'd' => [
'a' => null
]
];
$result = array_filter_recursive(
$array,
function ($value) {
if (is_array($value)) {
return !empty($value);
}
return ($value !== null);
}
);
$expected = [
'a'=> 'a',
'c' => [
'b' => 'b',
],
];
$this->assertSame($expected, $result);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.