Search code examples
phprecursionmultidimensional-arrayfilteringflatten

Recursively filter a multidimensional array and collect elements with a minimum string length


I have an array like this:

[
    [
        'key1' => 'hello im a text',
        'key2' => true,
        'key3' => '><><',
    ],
    [
        [
            'key1' => 'hello another text',
            'key2' => 'im a text too',
            'key3' => false,
        ],
        [
            'key1' = ')(&#',
        ],
    ],
    [
        'key1' => 'and so on',
    ]
]

How can I extract values which with a string length of 5 or more and populate a flat array?

Desired result:

[
    1 => 'hello im a text',
    2 => 'hello another text',
    3 => 'im a text too',
    4 => 'and so on',
]

Heres what I've done:

$found = array();
function search_text($item, $key)
{
    global $found;
    if (strlen($item) > 5)
    {
        $found[] = $item;
    }
}
array_walk_recursive($array, 'search_text');
var_dump($found);

but somehow it doesn't work.


Solution

  • Try something similar to this:

    function array_simplify($array, $newarray=array()) { //default of $newarray to be empty, so now it is not a required parameter
        foreach ($array as $i) { 
            if (is_array($i)) { //if it is an array, we need to handle differently
                $newarray = array_simplify($i, $newarray); // recursively calls the same function, since the function only appends to $newarray, doesn't reset it
                continue; // goes to the next value in the loop, we know it isn't a string
            }
            if (is_string($i) && strlen($i)>5) { // so we want it in the one dimensional array
                $newarray[] = $i; //append the value to $newarray
            }
        }
        return $newarray; // passes the new array back - thus also updating $newarray after the recursive call
    }
    

    My note: I haven't tested this, if there's bugs, please tell me and I'll try to fix them.