Create PHP array from MySQL column

Viewed 106796

mysql_fetch_array will give me an array of a fetched row. What's the best way generate an array from the values of all rows in one column?

12 Answers

If none of the above work, try:

while( $row = mysqli_fetch_assoc( $result)){
     $array[] = $row['id'];
}

mysql_fetch_assoc is deprecated.
// I'm using this for years and it works very good !! it's easy and logic
$translate = array();

while ($row = mysql_fetch_assoc($result))
  {
      $cullomnkey = $row['translshort']; // is what you want the key to be 
      $translate[$cullomnkey] = $row[$language]; // this is the key and the value in the array 
  }

Many years later, just another way. I don't know if its performance is better or worse than the while loop method.

For values without commas yo can do:

$res = mysql_query("SELECT GROUP_CONCAT(colname) AS values FROM tablename");
$row = mysql_fetch_assoc($res);
$arrOfValues = explode(',', $row['values']);

For a generic solution, you may use a separator:

$res = mysql_query("SELECT GROUP_CONCAT(colname SEPARATOR '##_sep_##') AS values FROM tablename");
$row = mysql_fetch_assoc($res);
$arrOfValues = explode('##_sep_##', $row['values']);
Related