I am trying to change multidimensional array index in running foreach:
$array = array(
array("apple", "orange"),
array("carrot", "potato")
);
$counter = 0;
foreach($array[$counter] as &$item) {
echo $item . " - ";
$counter = 1;
}
I supposed, that output would be apple - carrot - potato -, because in first run it takes value from zero array and then in next runs values from first array.
However, the output is apple - orange -
I tried add "&" before variable $item, but i guess it is not what I am looking for.
Is there any way to do it?
Thank you
// Well, i will try to make it cleaner:
This foreach takes values from $array[0], but in run i want to change index to 1, so in next repeat it will take values from $array[1]
Is that clear enough?
Note: I do not know how many dimensions my array has.
My purpose of this is not to solve this exact case, all I need to know is if is it possible to change source of foreach loop in run:
My foreach
$counter = 0;
foreach($array[$counter] as $item) {
echo $item . " - ";
}
is getting values from $array[0] right now. But inside it, I want to change $counter to 1, so next time it repeats, it will get values from $array[1]
$counter = 0;
foreach($array[$counter] as $item) {
echo $item . " - ";
$counter = 1;
}
I see, it is kind of hard to explain. This is how foreach should work:
Index of $array is $counter
First run
$array[0] -> as $item = apple
echo apple
wait, now counter changes to 1
Second run
$array[1] -> as $item = carrot
echo carrot
Third run
$array[1] -> as $item = potato
echo potato
END
I am really trying to make it clear as much as possible :D
apple-carrot-potato
orapple-orrange-carrot-potato
? – Bsienn May 5 at 9:44echo $array[0][0] . " - " . implode(" - ", $array[1]);
example – ssnake May 5 at 10:57foreach
gets array as value. As Shady wrote, you cannot change the iteration index offoreach
as the pointer to that is still pointing to the previous result. doing so won't change the pointer and continue as it is. you nee to use for or while loop, maybe recursion depending on your case. – Bsienn May 6 at 10:20