24

There is an associative array with only one pair key=>value.

I don't know it's key, but I need to get it's value:

$array = array('???' => 'value');
$value = // ??

$array[0] doesn't work.

How can I get it's value?

r5d
  • 579
  • 5
  • 24
Qiao
  • 16,565
  • 29
  • 90
  • 117

4 Answers4

56

You can also do either of the following functions to get the value since there's only one element in the array.

$value = reset( $array);
$value = current( $array);
$value = end( $array);

Also, if you want to use array_keys(), you'd need to do:

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

To get the value.

As some more options, you can ALSO use array_pop() or array_shift() to get the value:

$value = array_pop( $array);
$value = array_shift( $array);

Finally, you can use array_values() to get all the values of the array, then take the first:

$values = array_values( $array);
echo $values[0];

Of course, there are lots of other alternatives; some silly, some useful.

$value = pos($array);
$value = implode('', $array);
$value = current(array_slice($array, 0, 1));
$value = current(array_splice($array, 0, 1));
$value = vsprintf('%s', $array);
foreach($array as $value);
list(,$value) = each($array);
salathe
  • 51,324
  • 12
  • 104
  • 132
nickb
  • 59,313
  • 13
  • 108
  • 143
5

array_keys() will get the key for you

$keys = array_keys($array);
echo $array[$keys[0]];
John Conde
  • 217,595
  • 99
  • 455
  • 496
3

What you want is to retrieve the first item?

$value = reset($array);
$key = key($array);
Mathieu Dumoulin
  • 12,126
  • 7
  • 43
  • 71
0

You should use array_values

$newArray = array_values($array);
echo $newArray[0];
Farahmand
  • 2,731
  • 1
  • 24
  • 27