Amygdala
Amygdala

Reputation: 83

foreach inside foreach only returns last result?

I'm relatively new to PHP and arrays are giving me fits! I'm attempting to learn how to modify arrays and create new arrays from the modifications, but my attempts are only returning the last array key in the foreach loop.

function stuff() {
  $items = array('shirt', 'shoes', 'pants');
  $colors = array('red', 'blue', 'green');
  $list = array();
  foreach($items as $item) {
    foreach($colors as $color) {
      $list[$item] = array($color => 'available');
    }
  }
  return $list;
}

What I want this to return is:

Array
(
  [shirt] => Array
  (
    [red] => available
    [blue] => available
    [green] => available
  )

  [shoes] => Array
  (
    [red] => available
    [blue] => available
    [green] => available
  )

  [pants] => Array
  (
    [red] => available
    [blue] => available
    [green] => available
  )
)

However, it appears to be only returning the last item in the second array...

Array
(
  [shirt] => Array
  (
    [green] => available
  )

  [shoes] => Array
  (
    [green] => available
  )

  [pants] => Array
  (
    [green] => available
  )
)

Upvotes: 0

Views: 589

Answers (3)

The Humble Rat
The Humble Rat

Reputation: 4696

Here is the full code. Basically you are defining a new array each time you loop through the colors, replacing the previous.

function stuff() 
{
  $items = array('shirt', 'shoes', 'pants');
  $colors = array('red', 'blue', 'green');
  $list = array();
  foreach($items as $item) 
  {
      foreach($colors as $color) 
      {
         $list[$item][$color] = 'available';
      }
  }
 return $list;
}

print_r(stuff());

Upvotes: 0

STT LCU
STT LCU

Reputation: 4330

replace

 $list[$item] = array($color => 'available');

with

 $list[$item][$color] = 'available';

Upvotes: 3

user2680766
user2680766

Reputation:

Change $list[$item] = array($color => 'available'); to $list[$item][$color] = 'available'; and your problem will be solved.

Upvotes: 10

Related Questions