Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I need an array_keys_recursive()

$temp = array();
function show_keys($ar)
{
    foreach ($ar as $k => $v )
    {
        $temp[] = $k;
        if (is_array($ar[$k]))
        {
            show_keys ($ar[$k]);
        }
    }

    return $temp;
}

I tried using that function but it still only returns the first key.

like image 599
HyderA Avatar asked Oct 06 '10 13:10

HyderA


People also ask

How to get array keys PHP?

PHP: array_keys() function The array_keys() function is used to get all the keys or a subset of the keys of an array. Note: If the optional search_key_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the array are returned.

What is array_keys () used for?

The array_keys() is a built-in function in PHP and is used to return either all the keys of and array or the subset of the keys. Parameters: The function takes three parameters out of which one is mandatory and other two are optional.

How do you check if a key exists in an array PHP?

PHP array_key_exists() Function The array_key_exists() function checks an array for a specified key, and returns true if the key exists and false if the key does not exist.


2 Answers

Using SPL, looping over the keys is quite easy (store them in another array if you wish):

<?php
$arr = array_fill(0,8,range(0,3));
var_dump($arr);
foreach( new RecursiveIteratorIterator(
    new RecursiveArrayIterator($arr),
    RecursiveIteratorIterator::SELF_FIRST)
  as $key => $value){
        var_dump($key);
}
?>
like image 149
Wrikken Avatar answered Oct 26 '22 17:10

Wrikken


The main problem is that you are throwing away the results of the recursive show_keys() calls. You don't do anything with the return value.

Comments are inline.

function show_keys($ar)
{
    // Create new temp array inside function so each recursive call gets
    // a separate instance.
    $temp = array();

    foreach ($ar as $k => $v )
    {
        $temp[] = $k;

        // Use $v instead of $ar[$k].
        if (is_array($v))
        {
            // Combine results of recursive show_keys with $temp.
            $temp = array_merge($temp, show_keys($v));
        }
    }

    return $temp;
}
like image 44
John Kugelman Avatar answered Oct 26 '22 17:10

John Kugelman