Search code examples
phpmultidimensional-arrayarray-key

PHP, how to get the Array Key in Single Dimensional Array.


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;

Solution

  • 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)