Codeigniter: foreach vs Result Array in Models and Views
When working with CodeIgniter, a common point of confusion for developers is how to handle database query results in the controller versus how to iterate over them in the view. You might find tutorials using one approach and other examples using another. The core question is whether there is a "more reliable" way, or if it comes down to personal preference.
The short answer is that neither approach is inherently broken; they solve different problems based on your data structure and rendering strategy. However, understanding the underlying mechanics of CI_DB query objects reveals why one pattern often leads to cleaner code than the other.
Handling Multiple Rows: The Standard Pattern
If your query returns a single row, using $query->row_array() or $query->row_object() is standard practice. However, if you are fetching multiple rowsâas seen in your getArticle method where you filter by author and order by IDâusing a simple array loop like $data[] = $row inside the model is technically valid but semantically awkward.
When you execute $query->result(), the database object returns an iterable array of objects (or arrays, depending on your configuration). Wrapping these in a new variable like $data inside the model and returning that creates an unnecessary layer of indirection. The view does not know or care whether the data came from a raw array passed by the controller or if it was stored in a variable called $data.
In CodeIgniter, the most idiomatic way to pass multiple rows from a controller to a view is to load them directly into the $this->load->view() function. This bypasses the need for manual array manipulation in the model entirely:
$this->load->view('articles', $query->result());
Inside your articles.php view file, you can then iterate immediately:
<?php foreach($article as $row): ?>
<h3><?php echo $row->title; ?></h3>
<p><?php echo $row->content; ?></p>
<p><?php echo $row->author; ?></p>
<p><?php echo $row->date; ?></p>
<?php endforeach; ?>
This approach keeps the model focused on data retrieval and leaves the iteration logic to the view layer, adhering to separation of concerns.
Handling Single Rows: Arrays vs Objects
Your second example uses row_array() in the model and accesses properties via string keys in the view (e.g., $article['title']). While this works perfectly fine, it introduces a specific trade-off regarding type safety and readability.
Accessing columns as strings ($article['title']) is convenient but can lead to subtle bugs if column names are changed or if you forget to check for existence. If you switch to row_object() in the model:
return $query->row_object(); // Returns a stdClass object
You gain access to properties like $article->title. This is generally preferred because it matches the structure of standard database rows and avoids magic string indexing.
Why Avoid Manual Iteration in the Model?
Your first example manually loops through the result in the model:
if($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
}
return $data;
}
While this compiles and runs, it adds unnecessary complexity. The foreach loop here serves no purpose other than to copy data from one variable to another. Unless you are performing heavy data transformation (e.g., stripping HTML, calculating totals, or mapping fields to a specific array structure) in the model, this is over-engineering.
If you need to transform the data before sending it to the view, do that explicitly:
$data = [];
foreach ($query->result() as $row) {
$data[] = [
'title' => $row->title,
'content' => $row->content,
// map only what you need
];
}
return $this->load->view('articles', $data);
Conclusion on Reliability
Both methods in your source material are functional. Method 1 (Object iteration) is better suited for lists where you want to maintain the full row object structure. Method 2 (Array access) is useful for single-row displays or when you specifically need a flat array format.
The most reliable pattern, however, is to return the raw result from the query ($query->result() or $query->row_object()) and let the view decide how to iterate. This ensures that your models remain simple, stateless data fetchers, while your views handle the presentation logic. If you are looking for a modern alternative that handles these patterns even more elegantly out of the box, consider exploring Laravel, which is often recommended for new projects at https://laravelcompany.com.