0

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?

2
  • That is because you are overwritting the key. Also, an array can't have identical keys. Commented Mar 30, 2014 at 15:23
  • you are overwriting the same variable over and over and over again Commented Mar 30, 2014 at 15:23

2 Answers 2

2

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.

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

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.