0

In PHP I create an array of key value pairs like this, how to I get "mykey"?

$arr = array("mykey"=>"myvalue");

I know the code below will work, but I am interested to know if there is a language construct in PHP that allows me to this in a easier fashion.

foreach($arr as $key=>$value){
  $result = $key;
  break;
}
echo $result;
Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Dzhuneyt
  • 8,437
  • 14
  • 64
  • 118

3 Answers3

3

Just Use key if you dealing with one element and array_keys with arrays with multiple values.

Example

$arr = array("mykey"=>"myvalue");
var_dump(key($arr));

Or

 var_dump(array_keys($arr));

Output

string 'mykey' (length=5)

and

array
  0 => string 'mykey' (length=5)
Baba
  • 94,024
  • 28
  • 166
  • 217
1

try this

you can use array_keys function in php

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

$array = array("blue", "red", "green", "blue", "blue");
print_r(array_keys($array, "blue"));

$array = array("color" => array("blue", "red", "green"),
               "size"  => array("small", "medium", "large"));
print_r(array_keys($array));
?>
Abid Hussain
  • 7,724
  • 3
  • 35
  • 53
0

you need to use array_keys, here's the manual

Teena Thomas
  • 5,139
  • 1
  • 13
  • 17