PHP: Get key from array?

Industrial picture Industrial · Jul 23, 2010 · Viewed 235.4k times · Source

I am sure that this is super easy and built-in function in PHP, but I have yet not seen it.

Here's what I am doing for the moment:

foreach($array as $key => $value) {
    echo $key; // Would output "subkey" in the example array
    print_r($value);
}

Could I do something like the following instead and thereby save myself from writing "$key => $value" in every foreach loop? (psuedocode)

foreach($array as $subarray) {
    echo arrayKey($subarray); // Will output the same as "echo $key" in the former example ("subkey"
    print_r($value);
}

Thanks!

The array:

Array
(
    [subKey] => Array
        (
            [value] => myvalue
        )

)

Answer

vtorhonen picture vtorhonen · Jul 23, 2010

You can use key():

<?php
$array = array(
    "one" => 1,
    "two" => 2,
    "three" => 3,
    "four" => 4
);

while($element = current($array)) {
    echo key($array)."\n";
    next($array);
}
?>