1

Consider the following array:

$array[23] = array( [0] => 'FOO' [1] => 'BAR' [2] => 'BAZ' ); 

Whenever I want to work with the inner array, I do something like this:

foreach ($array as $key => $values) { foreach ($values as $value) { echo $value; } } 

The outer foreach-loop is there to split the $key and $value-pairs of $array. This works fine for arrays with many keys ([23], [24], ...)but seems redundant if you know beforehand that $array only has one key (23 in this case). In a case as such, isn't there a better way to split the key from the values? Something like

split($array into $key => $values) foreach ($values as $value) { echo $value; } 

I hope I made myself clear.

0

4 Answers 4

2

reset returns the first element of you array and key returns its key:

$your_inner_arr = reset($array); $your_key = key($array); 
Sign up to request clarification or add additional context in comments.

Comments

1

Yea, just get rid of your first foreach and define the array you're using with the known $key of your outter array.

foreach ($array[23] as $key =>$val): //do whatever you want in here endforeach; 

Comments

1

If an array has only one element, you can get it with reset:

$ar = array(23 => array('foo', 'bar')); $firstElement = reset($ar); 

Comments

0

A very succinct approach would be

foreach(array_shift($array) as $item) { echo $item; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.