1

I have an array. Say example

array('x'=>1);

this is having only one element. This array can change. Key change but only one element will be there. e.g. next time the array can be like --

array('y'=>1);

Now the problem is - I don't know the key name, I need the key name and the value as well.

But as it is having only one element I don't want to run a foreach.

Is it possible ?

Alice
  • 1,422
  • 1
  • 18
  • 30
  • 1
    Possible duplicate of [Get first key in a (possibly) associative array?](https://stackoverflow.com/questions/1028668/get-first-key-in-a-possibly-associative-array) – mickmackusa Jun 06 '17 at 03:15

3 Answers3

0

You should try with: array_search()

Tomasz Adamczyk
  • 251
  • 1
  • 7
  • no, the key can be anything... I don't want to search, I want to know the key... that's it – Alice Jun 03 '17 at 08:36
  • 1
    You know the value, right? So: „Searches the array for a given value and returns the first corresponding key if successful”. You can also look at: http://php.net/manual/en/function.key.php – Tomasz Adamczyk Jun 03 '17 at 08:38
0

Hope this will help you.

$key = array_keys($array)[0];
$value = $array[$key];
MH2K9
  • 11,951
  • 7
  • 32
  • 49
0

For that you can use key function

Try this here snippet here

$array=array('x'=>1);
echo key($array);//x
Sahil Gulati
  • 15,028
  • 4
  • 24
  • 42