Populate PHP Array from While Loop

Populate PHP Array from While Loop

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Populate PHP Array from While Loop

When you fetch data from a MySQL database using mysql_query and mysql_fetch_assoc, you are typically working with a resource that represents an active result set. Iterating through this set with a while loop is standard practice, but the moment inside that loop needs specific attention if your goal is to construct a PHP array. The most common mistake beginners make is failing to append values to an existing array variable, resulting in a script that runs without error but produces an empty or null result when checked later.

To populate an array, you must explicitly initialize it before the loop begins and then use functions like array_push or the shorthand $array[] syntax inside the loop body. For example:

$result = mysql_query("SELECT * FROM `Departments`");
$departments = []; // Initialize the array outside the loop

while($row = mysql_fetch_assoc($result)) {
    $departments[] = $row['department_name']; // Or push the whole row if needed
}

In this example, $departments is declared as an empty array before entering the while condition. Inside the loop, every time mysql_fetch_assoc returns a row, we append that data to $departments. If you omit the initialization line, PHP will throw a warning because it cannot modify a variable that hasn't been defined yet.

The choice of what to store in the array is also critical. The snippet in your source material uses mysql_fetch_assoc, which returns an associative array where keys match column names. If you need all columns for every department, pushing the entire $row into your collection works fine:

$all_data = [];
while($row = mysql_fetch_assoc($result)) {
    $all_data[] = $row;
}

However, if your downstream logic only cares about specific fields—say, just the department name and ID—you should extract those values to keep the resulting array lightweight. This avoids serializing unnecessary data into memory.

Performance Considerations with Deprecated Functions

It is impossible to discuss this pattern without addressing the underlying database extension. The mysql_* functions used in your source code are deprecated as of PHP 5.5 and removed entirely in PHP 7.0. If you are writing new code or maintaining a legacy project, you should migrate to MySQLi or PDO.

Using PDO offers better security practices through prepared statements and provides more flexible data handling. Here is how the same logic looks with PDO:

$stmt = $pdo->query("SELECT * FROM `Departments`");
$departments = [];

while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $departments[] = $row['department_name'];
}

The core principle remains identical: initialize the array, iterate, and append. The shift to PDO also allows you to handle errors more gracefully using exceptions rather than relying on error reporting levels.

Memory Management for Large Datasets

One subtle pitfall arises when dealing with large result sets. Loading an entire dataset into memory via a while loop before processing it can be inefficient if the dataset is massive. In such cases, it might be better to process each row immediately and discard it from memory rather than storing it all in an array. If you must store the data, consider using generators or streaming approaches to keep memory usage low.

For most applications involving moderate-sized tables like a list of departments, however, populating an array inside a while loop is the most straightforward and readable approach. Just ensure your initialization happens before the loop starts and your append logic is inside the loop body.

Our network