views:

349

answers:

4

Hi everybody,

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
        )

)
+1  A: 

Use the array_search function.

Example from php.net

$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');

$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array);   // $key = 1;
Sarfraz
Hi, updated my original post with an array example. Thanks!
Industrial
+2  A: 

$array = array(0 => 100, "color" => "red");
print_r(array_keys($array));

sushil bharwani
A: 

If it IS a foreach loop as you have described in the question, using $key => $value is fast and efficient.

Adam
A: 

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);
}
?>
vtorhonen
Hi! But key doesnt work in a foreach, right?
Industrial
Yes, that is correct. You need to use while-loop for key().
vtorhonen