Podarce
Podarce

Reputation: 493

Accessing nested associative array using array_keys (PHP)

I'm trying to access a nested associative array:

$data = array('1'=>'value1','2'=>'value2','3'=>array('one','two'))

The value of the key '3' is an array.

Since I need to cycle my values, I extracted the keys of given array:

$keys = array_keys($data);

and used to get the associated value with:

foreach(range(1, 10) as $val):
 echo "key: ".$keys[$val]; 
 echo "value: ".$data[$keys[$val]]; 
endforeach;

Now I would like to access the values related to '3'. Using $data[$keys[$val]] won't work cause I get back an array, not a value.

My question is: how can I access, for example to the value 'one' using a syntax close to $data[$keys[$val]] ?

Upvotes: 0

Views: 1896

Answers (1)

Ofir Baruch
Ofir Baruch

Reputation: 10346

You should add a condition to check if the value is a string or an array. If it's a string - simply echo it, otherwise - access the first value in that array (key = 0, will print 'one') or use another foreach loop to access all of those array's values.

foreach(range(1, 10) as $val):
 echo "key: ".$keys[$val]; 
 echo "value: ";
 if(is_array($data[$keys[$val]])){ //Is it an array?

  //echo 'one'
  echo $data[$keys[$val]][0];

  //or all the values with a loop
  foreach($data[$keys[$val]] as $val2){
   echo $val2;
   echo ",";
  }


 } else { //it's not an array, we can simply echo it.
  echo $data[$keys[$val]];
 }
endforeach;

Upvotes: 1

Related Questions