php - Get the first key in an associative array

154

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"
?>
373

Answer

Solution:

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

 echo key($data);

Note

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

245

Answer

Solution:

Try with this code:

reset($data);
$first_key = key($data);
769

Answer

Solution:

Now on PHP 7.3 >=

$firstKey = array_key_first($data);

People are also looking for solutions to the problem: php - How to use session variables to output logged in username and properties

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.