Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm attempting to make an array of users with ids and data. Normally the data is received from a database, but here it's hard-coded. I'm trying to make the users array return an associative array with an id and an array of data. For some reason, the arrays accessed with 'data' have no elements instead of each containing 5 and 6.

$users = array();
$users[] = array( "id" => 1, "data" => array() );
$users[] = array( "id" => 2, "data" => array() );
foreach( $users as $user_row ) {
    $user_row['data'] [] = 5;
    $user_row['data'] [] = 6;
}

How can I get the inner arrays to add in the data?

share|improve this question

5 Answers 5

up vote 2 down vote accepted

The foreach loop is creating copies of your sub-arrays, and so the changes made inside the loop do not persist. Add an ampersand to make $user_row reference the originals instead of making copies:

foreach( $users as &$user_row )
share|improve this answer

Either change your loop to

foreach( $users as &$user_row ) {
                   ^---

to create the $user_row as references back to the original array elements, or

foreach( $users as $key => $user_row) {
       $users[$key]['data'][] = 5;
       ...
}
share|improve this answer
$users = array();
$users[] = array( "id" => 1, "data" => array() );
$users[] = array( "id" => 2, "data" => array() );
foreach( $users as $key => $user_row ) {
    $users[$key]['data'] [] = 5;
    $users[$key]['data'] [] = 6;
}
share|improve this answer

foreach operates on a copy of the array, adding element inside it won't do anything. use this instead: for ($i = 0; $i < count($users); $i++) {...}

share|improve this answer

Unfortunately your version of PHP copies instead of references $user_row try

foreach( $users as &$user_row ) {
    $user_row['data'] [] = 5;
    $user_row['data'] [] = 6;
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.