views:

199

answers:

5

Hi, I've seen in the code I'm working on, the following:

foreach( $mysql_result as $row ) $site_id = $row->id;

$mysql_result is, of course a mysql_result, so this foreach is equivalent to a while( mysql_fetch_row() )

Sometimes, the result is known to yield only one row, but the code still has a "foreach" so it gives the impression of being a loop through many rows.

I tried using each() but doesn't work for this.

I know I could use mysql_fetch_row(), but the code should be DB independent so I can't use DB specific functions. Is there something like each() that works in this case just as the first iteration of foreach() ?

PS: what I do currently for readability is turn the previous example to this:

foreach( $mysql_result as $row ) break;
$site_id = $row->id;

So it's pretty obvious that the foreach will at most loop only once.

A: 

Is this what you want?

if ( 1 == count( $mysql_result ) )
{
  $row = current( $mysql_result );

  // could probably also do this unless the array isn't zero-indexed
  // $row = $mysql_result[0];
}
Peter Bailey
I think current() fails the same way each() does. Are you sure about it? I'll try it.
Petruza
A: 

If you only want one result, then you don't need to loop.

$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$site_id = $row['id'];
Zachary Burt
+3  A: 

I think what you want is instead of this:

foreach( $mysql_result as $row ) $site_id = $row->id;

Just this:

$site_id = $mysql_result[0]->id;
karim79
+1  A: 

PS: what I do currently for readability is turn the previous example to this:

foreach( $mysql_result as $row ) break;

Wrap that in a function so it's clear that it gets one row(and still are db independant)

function fetch_single_row($result) 
{
  foreach( $mysql_result as $row ) break;
  return $row;
}

Then your code would look like

$row = fetch_single_row($mysql_result);
$site_id = $row->id;

Now you won't have to wonder about all the strange foreach(..) break; statements all over the code.

leeeroy
A: 

You ould use a do loop

$i =0
do {
    $site_id = $mysql_result[$i++]->id;
} while ($i <= 0);
BeWarned