Php: how to get associative array with numeric index?

If I have:

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

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

+52
php associative-array key
Nov 04 '10 at
source share
8 answers

No. There is no key in your array [1] . You could:

  • Create a new array containing the keys:

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

    But the value of "one" is in $newArray[0] , not [1] .
    Label:

     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); 

It all depends on what exactly you want to do. The fact is that [1] does not correspond to β€œone” to any in which direction you turn it on.

+89
Nov 04 '10 at
source share
 $array = array( 'one' =>'value', 'two' => 'value2' ); $allKeys = array_keys($array); echo $allKeys[0]; 

It will display:

 one 
+46
Nov 04 '10 at
source share

If you plan to work with only one key, you can do this with a single line without having to store an array for all keys:

 echo array_keys($array)[$i]; 
+11
Feb 06 '15 at 10:40
source share

Or if you need it in a loop

 foreach ($array as $key => $value) { echo $key . ':' . $value . "\n"; } //Result: //one:value //two:value2 
+3
Nov 04 '10 at
source share
 $array = array( 'one' =>'value', 'two' => 'value2' ); $keys = array_keys($array); echo $keys[0]; // one echo $keys[1]; // two 
+2
Nov 04 '10 at 10:44
source share

You can do it as follows:

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

I haven't tried the code, but I'm sure it will work.

Good luck

0
Nov 04 '10 at 12:27
source share

key function helped me and is very simple

0
Jul 29 '14 at 15:52
source share

Expanding in response to Ram Dan, the key function is an alternative way to get the key of the current array index. 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 ''; } 
-one
Feb 01 '16 at 19:25
source share



All Articles