tags:

views:

184

answers:

1

Drupal provides these two methods for iterating through a db_query() result. For example,

$users = array();
$result = db_query('SELECT uid FROM {users} WHERE status=0 AND login=0');
while ($row = db_fetch_object($result)) {
    $users[] = $row->uid;
}

However, it seems that db_fetch_array($result) could be used just the same here, only with $row['uid'] on the next line.

What is the difference between these two methods? Are they completely interchangeable?

Source: http://api.drupal.org/api/group/database/6

A: 

The difference is that db_fetch_array() returns an array, whereas db_fetch_object() returns an object. Depending on the use-case, you might need one or the other.

It appears, at least given the snippet you provided, they are indeed—with a change in syntax like you mentioned—interchangeable for your use-case.

Edit

Drupal's db_fetch_object() and db_fetch_array() are inherited from PHP's *_fetch_object and *_fetch_array: Drupal merely abstracts PHP's database specific versions so a Drupal developer doesn't have to care what database is used in the backend.

So, the same reasons why they both exist in PHP are the same reasons why they exist in Drupal. They provide flexibility to developers: some use-cases require arrays, some require objects.

In Drupal core, db_fetch_object() is favored far more than db_fetch_array(): you can see how each are used within core by going to each function's API page and clicking on the header n functions call functionname.

The reason for this bias towards db_fetch_object is mainly preference and ease of maintenance: it's less characters to say $object->property than it is to say $object['property']. A lot of code style in Drupal is based on years of convention.

You can use either, but think whether it makes sense, semantically, for your data to be an object or an array. For example, if you wanted to take advantage of PHP's plethora of array functions (like array_merge(), which doesn't have a simple object analogue), you might opt to buck convention and use db_fetch_array().

All things being equal, *_fetch_object() is identical to *_fetch_array in terms of speed, but the resulting object from the former takes up slightly more memory than the resulting array from the latter.

Mark Trapp
1) Can you give an example where you'd use one rather than the other?2) Is there a performance difference between the two?
feedbackloop
Sure; I've revised my answer to provide more background.
Mark Trapp

related questions