PHP: Get key from array?

2019-01-31 05:29发布

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
        )

)

8条回答
时光不老,我们不散
2楼-- · 2019-01-31 05:54

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;
查看更多
We Are One
3楼-- · 2019-01-31 05:54

Another way to use key($array) in a foreach loop is by using next($array) at the end of the loop, just make sure each iteration calls the next() function (in case you have complex branching inside the loop)

查看更多
干净又极端
4楼-- · 2019-01-31 05:55

Try this

foreach(array_keys($array) as $nmkey)
    {
        echo $nmkey;
    }
查看更多
Deceive 欺骗
5楼-- · 2019-01-31 05:57

If you want to be in a foreach loop, then foreach($array as $key => $value) is definitely the recommended approach. Take advantage of simple syntax when a language offers it.

查看更多
劳资没心,怎么记你
6楼-- · 2019-01-31 06:01
$foo = array('a' => 'apple', 'b' => 'ball', 'c' => 'coke');

foreach($foo as $key => $item) {
  echo $item.' is begin with ('.$key.')';
}
查看更多
叛逆
7楼-- · 2019-01-31 06:01

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

查看更多
登录 后发表回答