Populate PHP Array from While Loop Populate PHP Array from While Loop arrays arrays

Populate PHP Array from While Loop


Build an array up as you iterate with the while loop.

$result = mysql_query("SELECT * FROM `Departments`");$results = array();while($row = mysql_fetch_assoc($result)){   $results[] = $row;}

Alternatively, if you used PDO, you could do this automatically.


This will do the trick:

$rows = array();$result = mysql_query("SELECT * FROM `Departments`");while($row = mysql_fetch_assoc($result)){  $rows[] = $row;}


This has been one of the fastest ways for me to create (multi-dimensional) arrays. I'm not sure if you want all of your results smooshed into one array or not.

// Read records$query = "SELECT * FROM `Departments`"; $query = mysql_query($query);// Put them in arrayfor($i = 0; $array[$i] = mysql_fetch_assoc($query); $i++) ;// Delete last empty onearray_pop($array);

You can use print_r($array) to see the results.