How to store values from foreach loop into an array?

Brad picture Brad · Jun 15, 2010 · Viewed 390.1k times · Source

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);

Answer

Andy E picture Andy E · Jun 15, 2010

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);