Php – How to store values from foreach loop into an array

foreachPHP

Need to store values from foreach loop into an array, need help doing that.

The code below does not work, only stores the last value, tried $items .= ..., but that is not doing the trick either, any help will be appreciated.

foreach($group_membership as $i => $username) {
    $items = array($username);
}

print_r($items);

Best Answer

Declare the $items array outside the loop and use $items[] to add items to the array:

$items = array();
foreach($group_membership as $username) {
 $items[] = $username;
}

print_r($items);