$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.
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.
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.
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.
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);
}
?>
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With