PHP: get the key to an array?

I'm sure this is a super simple and built-in function in PHP, but I haven't seen it yet.

Here is what I am doing at the moment:

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

Can I do something like the following and thereby save myself from writing "$ key => $ value" in each 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); } 

Thank!

Array:

 Array ( [subKey] => Array ( [value] => myvalue ) ) 
+51
arrays php multidimensional-array key
Jul 23 '10 at 11:54
source share
9 answers

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); } ?> 
+62
Jul 23 '10 at 12:28
source share
— -

Use array_search .

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; 
+40
Jul 23 '10 at 11:56
source share
 $foo = array('a' => 'apple', 'b' => 'ball', 'c' => 'coke'); foreach($foo as $key => $item) { echo $item.' is begin with ('.$key.')'; } 
+29
Aug 26 2018-12-12T00:
source share
 $array = array(0 => 100, "color" => "red"); print_r(array_keys($array));
$array = array(0 => 100, "color" => "red"); print_r(array_keys($array)); 
+13
Jul 23 2018-10-23T00:
source share

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

+5
Jul 23 '10 at 12:17
source share

If you want to be in the foreach , then foreach($array as $key => $value) definitely recommended. Use simple syntax when language offers it.

+1
Jun 05 '15 at 0:22
source share

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

0
02 Feb '13 at 23:32
source share

try it

 foreach(array_keys($array) as $nmkey) { echo $nmkey; } 
0
Jun 01 '16 at 12:27
source share

Here is a general solution that you can add to your Array library. All you have to do is specify the appropriate value and the target array!

PHP manual: array_search () (similar to .indexOf () in other languages)

 public function getKey(string $value, array $target) { $key = array_search($value, $target); if ($key === null) { throw new InvalidArgumentException("Invalid arguments provided. Check inputs. Must be a (1) a string and (2) an array."); } if ($key === false) { throw new DomainException("The search value does not exists in the target array."); } return $key; } 
0
May 08 '19 at 21:27
source share



All Articles