0

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]] ?

1
  • Is there a specific reason for how you iterate the array? A simple foreach($data as $key => $value) {} would achieve the same result. Commented Nov 15, 2017 at 14:00

1 Answer 1

1

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;
Sign up to request clarification or add additional context in comments.

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.