8

I've got a multidimensional array returned by an API call. The values into this array are stored with a key like this :

Array(["BTC_XRP"] => 1)

I can get the values of the Array by getting them using the keys (like BTC_XRP), but what if I need to get the value using the Index?

For example, how do I get each value of the Array using a for loop if I can't get the values by the Index?

Since the Array is composed by something like 100 values, I need to echo every one using a for loop, but this gives me this error :

Notice: Undefined offset: 0

Is it possible to get to a value using the Index instead of the Key?

Furthermore, I'd like to get the Key by the Index. If I want to get the Key of the first value, I'd like to get it using the 0 Index.

4
  • use foreach instead of a for loop. Commented Apr 2, 2017 at 11:23
  • Have you tried $array[0] where 0 is the number in the array to access it. E.g from your question echo $array[0] should output 1. Or am I missing the point? Commented Apr 2, 2017 at 11:25
  • @Ashley Prescott Yes that's exactly what I did, but PHP doesn't let you get a value by Index if it's stored as Key. Commented Apr 2, 2017 at 11:29
  • One of those questions with harmfully confused titles Commented Jun 27, 2023 at 12:18

2 Answers 2

8

Sounds like you are in search of array_keys (to get key by index) and array_values (to get value by index) functions:

$array = array("BTC_XRP" => 1, "EUR_XRP" => 234, "USD_XRP" => 567);
$keys   = array_keys( $array );
$values = array_values( $array );

var_dump( $keys[1] ); // string(7) "EUR_XRP"
var_dump( $values[1] ); // int(234)

Or use a foreach as Joshua suggests.

Sign up to request clarification or add additional context in comments.

Comments

4

This question has a confusing title. What the OP needed is simply how to iterate over associative array. And the answer is just as silly:

foreach ($array as $key => $value) {
    echo "Key: $key, value: $value";
}

But the title, that attracts people from Google search, explicitly asks how to get a certain value from associative array by its position (or "index"). For this you need a function called array_slice():

$array = array('a'=>'apple', 'b'=>'banana', '42'=>'pear', 'd'=>'orange');

$index = 2;
$elem = array_slice($array, $index, 1, true);
$key = key($elem);
$value = reset($elem);
echo "Key: $key, value: $value"; // Key: 42, value: pear

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.