Get key value from associative array php

If I have:

$array = array( 'one' =>'value', 'two' => 'value2' );

how do I get the string one back from $array[1] ?

asked Nov 4, 2010 at 10:36

1

You don't. Your array doesn't have a key [1]. You could:

  • Make a new array, which contains the keys:

    $newArray = array_keys($array);
    echo $newArray[0];
    

    But the value "one" is at $newArray[0], not [1].
    A shortcut would be:

    echo current(array_keys($array));
    
  • Get the first key of the array:

     reset($array);
     echo key($array);
    
  • Get the key corresponding to the value "value":

    echo array_search('value', $array);
    

This all depends on what it is exactly you want to do. The fact is, [1] doesn't correspond to "one" any which way you turn it.

answered Nov 4, 2010 at 10:43

decezedeceze

497k81 gold badges718 silver badges865 bronze badges

0

$array = array( 'one' =>'value', 'two' => 'value2' );

$allKeys = array_keys($array);
echo $allKeys[0];

Which will output:

one

answered Nov 4, 2010 at 10:38

kennytmkennytm

497k100 gold badges1061 silver badges994 bronze badges

0

If you only plan to work with one key in particular, you may accomplish this with a single line without having to store an array for all of the keys:

echo array_keys($array)[$i];

answered Feb 6, 2015 at 22:40

Get key value from associative array php

StarCrashrStarCrashr

4264 silver badges11 bronze badges

3

Or if you need it in a loop

foreach ($array as $key => $value)
{
    echo $key . ':' . $value . "\n";
}
//Result: 
//one:value
//two:value2

answered Nov 4, 2010 at 10:42

DeckoDecko

17.6k2 gold badges26 silver badges39 bronze badges

2

$array = array( 'one' =>'value', 'two' => 'value2' );
$keys  = array_keys($array);
echo $keys[0]; // one
echo $keys[1]; // two

answered Nov 4, 2010 at 10:44

Get key value from associative array php

Alex PliutauAlex Pliutau

20.8k26 gold badges108 silver badges142 bronze badges

You might do it this way:

function asoccArrayValueWithNumKey(&$arr, $key) {
   if (!(count($arr) > $key)) return false;
   reset($array);
   $aux   = -1;
   $found = false;
   while (($auxKey = key($array)) && !$found) {
      $aux++;
      $found = ($aux == $key);
   }
   if ($found) return $array[$auxKey];
   else return false;
}

$val = asoccArrayValueWithNumKey($array, 0);
$val = asoccArrayValueWithNumKey($array, 1);
etc...

Haven't tryed the code, but i'm pretty sure it will work.

Good luck!

answered Nov 4, 2010 at 12:27

If it is the first element, i.e. $array[0], you can try:

echo key($array);

If it is the second element, i.e. $array[1], you can try:

next($array);
echo key($array);

I think this method is should be used when required element is the first, second or at most third element of the array. For other cases, loops should be used otherwise code readability decreases.

answered Nov 6, 2019 at 12:00

VivekPVivekP

711 silver badge6 bronze badges

The key function helped me and is very simple:

The key() function simply returns the key of the array element that's currently being pointed to by the internal pointer. It does not move the pointer in any way. If the internal pointer points beyond the end of the elements list or the array is empty, key() returns NULL.

Example:

 'apple',
        'fruit2' => 'orange',
        'fruit3' => 'grape',
        'fruit4' => 'apple',
        'fruit5' => 'apple');

    // this cycle echoes all associative array
    // key where value equals "apple"
    while ($fruit_name = current($array)) {
        if ($fruit_name == 'apple') {
            echo key($array).'
'; } next($array); } ?>

The above example will output:

fruit1
fruit4
fruit5

Get key value from associative array php

Alfie

2,2862 gold badges26 silver badges43 bronze badges

answered Jul 29, 2014 at 15:52

1

One more example:

Get the most frequent occurrence(s) in an array:

PHP >= 7.3:

$ php --version
PHP 7.4.3 (cli) (built: Oct  6 2020 15:47:56) ( NTS )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
    with Zend OPcache v7.4.3, Copyright (c), by Zend Technologies

$ php -a
Interactive mode enabled

php > $a = array_count_values(array('abc','abc','def','def','def'));
php > var_dump($a);
array(2) {
  ["abc"]=>
  int(2)
  ["def"]=>
  int(3)
}
php > arsort($a);
php > var_dump($a);
array(2) {
  ["def"]=>
  int(3)
  ["abc"]=>
  int(2)
}
php > var_dump(array_key_first($a));
string(3) "def"
php > var_dump(array_keys($a)[1]);
string(3) "abc"

If you have the key, you can easily query the value (= the frequency).

answered Apr 21, 2021 at 16:32

qräbnöqräbnö

2,38925 silver badges32 bronze badges

just posting another solution for those that array_keys() is not working

$myAssociativeArray = [
  'name' => 'sun',
  'age' => 21
);

$arrayKeys = [];
foreach($myAssociativeArray as $key => $val){
    array_push($arrayKeys, $key);
}

print_r($arrayKeys)

// ['name', 'age']

answered Oct 13, 2021 at 13:25

Expanding on Ram Dane's answer, the key function is an alternative way to get the key of the current index of the array. You can create the following function,

    function get_key($array, $index){
      $idx=0;
      while($idx!=$index  && next($array)) $idx++;
      if($idx==$index) return key($array);
      else return '';
    }

answered Feb 1, 2016 at 19:25

AurovrataAurovrata

1,76223 silver badges42 bronze badges

How get key from value in array in PHP?

If you have a value and want to find the key, use array_search() like this: $arr = array ('first' => 'a', 'second' => 'b', ); $key = array_search ('a', $arr); $key will now contain the key for value 'a' (that is, 'first' ).

How do you iterate through an associative array in PHP?

The foreach() method is used to loop through the elements in an indexed or associative array. It can also be used to iterate over objects. This allows you to run blocks of code for each element.

How get key of multidimensional array in PHP?

Retrieving Values: We can retrieve the value of multidimensional array using the following method:.
Using key: We can use key of the associative array to directly retrieve the data value. ... .
Using foreach loop: We can use foreach loop to retrieve value of each key associated inside the multidimensional associative array..

How do you find array keys?

The array_keys() function is used to get all the keys or a subset of the keys of an array. Note: If the optional search_key_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the array are returned. Specified array.