1

I have a multidimensionel array of different departments, and a want to loop through it using a foreach loop, but for some reason, the foreach loop grabs the values under the first key through every iteration.

The array looks like this:

$departmentArray = Array ( [0] => Array ( [dpt_id] => 5 [dpt_name] => Administration [dpt_employees] => Array ( [0] => Array ( [started] => 2000-06-01 [stopped] => 9999-99-99 [empl_id] => 21 ) [1] => Array ( [started] => 2000-06-01 [stopped] => 2010-01-01 [empl_id] => 23 ) ) ) [1] => Array ( [dpt_id] => 6 [dpt_name] => Warehouse [dpt_employees] => Array ( [0] => Array ( [started] => 2000-10-01 [stopped] => 2012-01-01 [empl_id] => 30 ) [1] => Array ( [started] => 2007-10-17 [stopped] => 9999-99-99 [empl_id] => 197 ) ) ) ) 

And the foreach loop looks like this:

foreach($departmentArray as $key => $value) { print_r($key); print_r($value['dpt_name']); } 

And this prints:

0 Administration 1 Administration. 

Does anyone know, why the loop does not move forward in the array and grab the value (Warehouse) under key/index 1 during its second iteration?

2
  • 4
    No, this code would not print that. If your own code prints it, you are doing something different. Possibly iterating by reference and changing the values? Commented Sep 18, 2012 at 13:45
  • Thank you for answering. You are right, I am iterating by reference earlier in the code, where I use the same name, I will look into it now. Commented Sep 18, 2012 at 14:03

1 Answer 1

2

Total stab into the dark:

You have used $value in a foreach loop before as reference, like so:

foreach ($foo as &$value) { ... } foreach ($departmentArray as $key => $value) { ... } 

This is a well known side-effect of references. unset($value) after the first loop.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your stab in the dark, I think you are right, as I am iterating by reference earlier i the code. Should i unset() the $value in the first loop inside the curly brackets?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.