Sikander Sikander - 4 months ago 9
PHP Question

PHP: Adding an element in array in foreach loop

I want to add a new index to an array and add values to it in a loop.

for example i've following array in a loop

[books] => Array
(
[0] => stdClass Object
(
[id] => 1
[user_id] => 5
[book_id] => 1
[date_issue] => 2016-07-24 00:00:00
[date_return] => 2016-07-25 00:00:00
)

[1] => stdClass Object
(
[id] => 5
[user_id] => 5
[book_id] => 2
[date_issue] => 2016-07-24 00:00:00
[date_return] => 2016-07-25 00:00:00
)

)


This is how i am getting it

foreach ($query_books->result() as $key => $value) {
$result['books']= $query_books->result();
}
print_r($result);


now in each iteration i want to add a new index after
[date_return]
how do i do that please help

Answer

First, your foreach loop doesn't look like it really needs to be a loop. You aren't doing anything with $key or $value; it's really just overwriting $result['books'] repeatedly with the result of $query_books->result(). You should get the same result with just:

$result['books'] = $query_books->result();

After you have that, you can loop over it and add new information:

foreach ($result['books'] as $book) {
    $book->new_index = 'new value';
}
print_r($result);

The items in $result['books'] are not actually arrays; they are stdClass Objects. This is why object syntax ($book->new_index) is used to add the property rather than array syntax ($book['new_index']).


Theoretically, if you did have an array of arrays, it would be necessary to use a reference (&$book rather than $book) in your foreach loop in order to modify them, because foreach creates a copy of each item as it iterates:

foreach ($result['books'] as &$book) {   // use a reference
    $book['new_index'] = 'new value';
}
unset($book); // unset the reference

print_r($result);

It is not necessary to use a reference to modify an array of objects like you have, because the copy of the object identifier in the foreach loop still points to the same object. You can read about this in more detail in the PHP manual.

Comments