Skip to content

Instantly share code, notes, and snippets.

@david4worx
Last active April 27, 2020 01:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save david4worx/1a991a705a52d8f9b16b to your computer and use it in GitHub Desktop.
Save david4worx/1a991a705a52d8f9b16b to your computer and use it in GitHub Desktop.
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