paul kendal23
paul kendal23

Reputation: 185

How to add to an array in a loop

I’m trying to add to an array in a loop but only the first element in the loop is added.

The array

array (size=7)
  0 => 
    array (size=2)
      'id' => int 1
      'name' => string 'john' (length=11)
  1 => 
    array (size=2)
      'id' => int 2
      'name' => string 'adam' (length=13)
  2 => 
    array (size=2)
      'id' => int 3
      'name' => string 'mary' (length=11)

My loop

foreach ($loops as $key => $loop) {
    $idArray['id'] =  $loop['id'];
}
var_dump($idArray); die();

Did I do anything wrong?

Upvotes: 0

Views: 97

Answers (2)

robbmj
robbmj

Reputation: 16516

If you want the ordinal values of the $idarray to be the primary key values of what you are iterating over you can do this.

$loops = array(array('id' => 1, 'name' => 'john'), /* ... */);

foreach ($loops as $key => $loop)
{             
    $idArray[$loop['id']] =  $loop;
}
var_dump($idArray); die();

var_dump will reveal this structure

array (size=7)
  1 => 
    array (size=2)
      'id' => int 1
      'name' => string 'john' (length=4)
  2 => 
    array (size=2)
      'id' => int 2
      'name' => string 'adam' (length=4)
  3 => 
    array (size=2)
      'id' => int 3
      'name' => string 'mary' (length=4)

Upvotes: 0

Tobias Golbs
Tobias Golbs

Reputation: 4616

You overwrite your old value by assigning the new value to the array. An array can't have identical keys.

Try this:

foreach ($loops as $key => $loop)
{             
    $idArray['id'][] =  $loop['id'];
}
var_dump($idArray); die();

So you add items to an array inside your array.

Upvotes: 2

Related Questions