S
S
Shimpanze2020-05-28 12:36:38
PHP
Shimpanze, 2020-05-28 12:36:38

Why doesn't "array_walk_recursive" work in this case?

Hello!

Can you explain why the "array_walk_recursive" function cannot determine that the value of the current key is an array?

Example:

$test = array(
    'q' => 'foo',
    'w' => array(
        'phone' => array (
            '111',
            '222',
            'leo' => array ( '333', '444' ),
        ),
    ),
    'e' => 'bar'
);

array_walk_recursive( $test, function( $v, $k ) {
    if ( is_array( $v ) ) print "да - значение этого ключа - массив\n";
    else print "нет - значение этого ключа - не массив\n";
});


Sandbox

Thanks!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
smilingcheater, 2020-05-28
@Shimpanze

Um, well, kind of because it's an array_walk_recursive.
If it encounters an array as the value of the current key, it enters it and starts applying the callback to the scalar elements in it.
---
Final answer: write your own recursive function to traverse the array. For example like this:

function recursiveProcess($array) {
    foreach ($array as $key => $value) {
        if ($key == 'car' && is_array($value) && isset($value['color'])) {
            // Нашли!
        }
        
        if (is_array($value)) {
            // Встретили массив - заходим в него
            recursiveProcess($value);
        }
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question