Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Get key from array?

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         )  ) 
like image 206
Industrial Avatar asked Jul 23 '10 11:07

Industrial


People also ask

How get key from value in array in PHP?

If you have a value and want to find the key, use array_search() like this: $arr = array ('first' => 'a', 'second' => 'b', ); $key = array_search ('a', $arr); $key will now contain the key for value 'a' (that is, 'first' ).

What is array_keys () used for?

The array_keys() function returns all the keys of an array. It returns an array of all the keys in array.

How get the key of an object in PHP?

You can cast the object to an array like this: $myarray = (array)$myobject; And then, for an array that has only a single value, this should fetch the key for that value. $value = key($myarray);

What is the key in an array?

key is just a variable that holds an array index. This example: var key = 7; var item = array[key]; gets you the same value as this: var item = array[7];


2 Answers

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; 
like image 45
Sarfraz Avatar answered Sep 17 '22 19:09

Sarfraz


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); } ?> 
like image 198
vtorhonen Avatar answered Sep 19 '22 19:09

vtorhonen