php - 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 usekey
, but I read (on this site), that's it's less efficient.
So I'm usingcurrent(array_keys($data))
.
Is there another way of doing this? Will I always get the first key when I usecurrent(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"
?>
Answer
Solution:
echo current(array_keys($data));
is a long process just usekey
Note
$data = json_decode($json, true);
would reset the array ... so no need to callreset
againAnswer
Solution:
Try with this code:
Answer
Solution:
Now on PHP 7.3 >=