Home >Backend Development >PHP Tutorial >How to Correctly Store Values from a foreach Loop into an Array in PHP?
Storing Values from Foreach Loop into an Array
When iterating over data in a foreach loop, sometimes you may need to store the values into an array. However, simply assigning the value inside the loop often stores only the last value.
Example Code with Issue:
foreach($group_membership as $username) { $items = array($username); } print_r($items);
Solution:
To store all values, declare the array outside the loop and use $items[] to add each item:
$items = array(); foreach($group_membership as $username) { $items[] = $username; } print_r($items);
By following this modified code, the $items array will contain all the usernames from the $group_membership array, allowing you to work with them efficiently.
The above is the detailed content of How to Correctly Store Values from a foreach Loop into an Array in PHP?. For more information, please follow other related articles on the PHP Chinese website!