Skip to content
Advertisement

Get the first key in an associative array

I’m trying to get the first key of an array in an associative array like below. I know I can use key, but I read (on this site), that’s it’s less efficient.

So I’m using current(array_keys($data)).

Is there another way of doing this? Will I always get the first key when I use current(array_keys($data))? That’s what I scared off.

I’m using php 5.3.18. This is the way the script starts off.

<?php
$json = '{"user":"norman","city":"san jose","type":"editor"}';

$data = json_decode($json, true);

echo current(array_keys($data));
//Output I need is "user"
?>

Advertisement

Answer

echo current(array_keys($data)); is a long process just use key

 echo key($data);

Note

$data = json_decode($json, true); would reset the array … so no need to call reset again

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement