0

Hope you can help me on this one. I have this php array variable.

$countries = [
"Argentina" => ['Buenos Aires','Cordoba','Rosario'],
"USA" => ['San Fransisco','Dallas','Nueva Yotk'],
"Brasil" => ['Rio','San Pablo','Salvador']

and I want to print, for example: Argentina, Córdoba or USA, Nueva York, etc. I mean, select one element of one of the subarrays. How can I accomplish that? I've tried

print_r(array_values($countries));

it prints ALL values, but I want to print a specific value of the key/s

Thanks!

GTWerber
  • 3
  • 2
  • Try `echo($countries['USA'][0]);`, `echo($countries['USA'][1]);`, etc. Probably should read: https://www.php.net/manual/en/language.types.array.php – ficuscr Jul 10 '19 at 17:34
  • Possible duplicate of [PHP - Getting the index of a element from a array](https://stackoverflow.com/questions/3764654/php-getting-the-index-of-a-element-from-a-array) – ficuscr Jul 10 '19 at 17:37

1 Answers1

1
$countries = [
    "Argentina" => ['Buenos Aires','Cordoba','Rosario'],
    "USA" => ['San Fransisco','Dallas','Nueva Yotk'],
    "Brasil" => ['Rio','San Pablo','Salvador']
];

In the array above, Argentina, USA, Brasil are the array keys. To get to array keys, you can make use of function array_keys();

Code:

$keys = array_keys($countries);
print_r($keys);

Output:

Array ( [0] => Argentina [1] => USA [2] => Brasil )

To reach specific value of specific key, you can:

echo $countries['Argentina'][0]

Output:

Buenos Aires

You can also access it with key index, as $keys is also an array as:

echo $countries[$keys[1]][1];

Output:

Dallas

LIGHT
  • 5,604
  • 10
  • 35
  • 78