Get First Key in a (Possibly) Associative Array

Get first key in a (possibly) associative array?

2019 Update

Starting from PHP 7.3, there is a new built in function called array_key_first() which will retrieve the first key from the given array without resetting the internal pointer. Check out the documentation for more info.


You can use reset and key:

reset($array);
$first_key = key($array);

It's essentially the same as your initial code, but with a little less overhead, and it's more obvious what is happening.

Just remember to call reset, or you may get any of the keys in the array. You can also use end instead of reset to get the last key.

If you wanted the key to get the first value, reset actually returns it:

$first_value = reset($array);

There is one special case to watch out for though (so check the length of the array first):

$arr1 = array(false);
$arr2 = array();
var_dump(reset($arr1) === reset($arr2)); // bool(true)

Get the first key in an associative array

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

Return first key of associative array in PHP

Although array_shift(array_keys($array)); will work, current(array_keys($array)); is faster as it doesn't advance the internal pointer.

Either one will work though.

Update

As @TomcatExodus noted, array_shift(); expects an array passed by reference, so the first example will issue an error. Best to stick with current();

How to get first n keys in associative array in PHP?

Sort the array in reverse order keeping association with arsort(). Then take a slice of the array (first three elements).

arsort( $scores );
$topScores = array_slice( $scores, 0, 3 );

You can then use implode to generate a string from the sliced array.


Rizier123 pointed out you wanted the keys in the string, so you'd need to implode the keys. Something like

$topScoresStr = implode( ', ', array_keys( $topScores ) );

How to get the first item from an associative PHP array?

reset() gives you the first value of the array if you have an element inside the array:

$value = reset($array);

It also gives you FALSE in case the array is empty.

How to echo the first key value of an associative array without knowing the name of the key

<?php
$data =
[
'id-1.txt' => 'uploads/id-1.jpg',
'id-2.txt' => 'uploads/id-2.jpg',
'id-3.txt' => 'uploads/id-3.jpg'
];

$copy = $data;

echo reset($copy);
unset($copy);

Output:

uploads/id-1.jpg

Here using a copy for no side effects.

PHP get first and forth value of an associative array

use array_keys?

$keys = array_keys($your_array);

echo $your_array[$keys[0]]; // 1st key
echo $your_array[$keys[3]]; // 4th key

PHP Getting First Element Of Associative Array

Try using key($fr_coin_multiplier_asc). Per the PHP documentation:

key() returns the index element of the current array position.



Related Topics



Leave a reply



Submit