Brad Brad - 4 months ago 18
PHP Question

need to store values from foreach loop into array

Need to store values from foreach loop into an array, need help doing that. 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.

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

print_r($items);
?>

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