tags:

views:

161

answers:

6

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);
?>
+8  A: 

Use

$items[] = $username;
Sjoerd
Just make sure `$items = array();` appears before the loop.
Skilldrick
+6  A: 

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);
Andy E
Also, don't extract the key (`$i`) if you're not going to use it.
kemp
@kemp, you're right. I just copy/pasted the OP's code before, I've altered it now.
Andy E
+1  A: 
sushil bharwani
+3  A: 

Try

$items = array_values ( $group_membership );
Adam
Well I assume the foreach loop is doing more than that, otherwise this is the best solution.
kemp
A: 

mh.. I can try to do my answer

you wrote this:

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

print_r($items);
?>

and in your case I do this:

<?php
$items = array();
foreach ($group_membership as $username) { // If you need the pointer (but I don't think) you have to add '$i => ' before $username
 $items[] = $username;
} ?>

as you show on your question seems that you need an array of user that are in a group or more group :) In this case I prefer a good sql query with a simple while ;)

<?php
$query = "SELECT `username` FROM group_membership AS gm LEFT JOIN users AS u ON gm.`idUser` = u.`idUser`";
$result = mysql_query($query);
while ($record = mysql_fetch_array($result)) { $items[] = $username; } ?>

'while' is more faster, but the last example is only a result of a observation :)

Have a nice day

Paper-bat
A: 

$items=array(); $j=0; foreach($group_membership as $i => $username) { $items[$j++]=$username; }

just try this in your code...

neha