Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php: how to get associative array key from numeric index?

If I have:

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

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

like image 574
Mazatec Avatar asked Nov 04 '10 10:11

Mazatec


People also ask

How do you find the key of an associative array?

Answer: Use the PHP array_keys() function You can use the PHP array_keys() function to get all the keys out of an associative array.

How do I get associative array in PHP?

Answer: Use the PHP array_values() function You can use the PHP array_values() function to get all the values of an associative array.

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' ).

What is array_keys () used for?

The array_keys() function returns all the keys of an array. It returns an array of all the keys in array.


1 Answers

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.

like image 157
deceze Avatar answered Sep 28 '22 06:09

deceze