tags:

views:

61

answers:

3

I have this code

public function getList()
{
 $array = array();

 $r = mysql_query( "SELECT * FROM hobby ORDER BY hobby_name ASC" );
 while( $ro = mysql_fetch_object( $r ) )
 {
  array_push( $array , $ro );
 }

 if ( count( $array ) > 0 )
  return $array;
 else
  return false;
}

And was wondering if there is an easier way of doing this?

This code first gets all out of the database, pushes it into anarray, checks its count and returns the array or false.

When I get it into my $array I need to make foreach to this object to pase it.

+2  A: 

Hi,

I would probably do something like you proposed.

One thing I would change : instead of this :

array_push( $array , $ro );

I would probaly use :

$array[] = $ro;

To avoid a function call, which seems useless in this case (both syntaxes should do the same).


Also, I would always return an array : the function is called "getList", so, in my opinion, it should return... a list.

Even when there is no element, it should return an empty list (ie, empty array), and not a boolean false.

This also means you can just return your $array, not having to count the number of elements it contains ; so, I suppose I would end up with something like this :

public function getList()
{
  $array = array();
  $r = mysql_query( "SELECT * FROM hobby ORDER BY hobby_name ASC" );
  while( $ro = mysql_fetch_object( $r ) )
  {
    $array[] = $ro;
  }
  return $array;
}
Pascal MARTIN
+3  A: 

You should return an empty array instead of false, then you can run it through foreach without PHP generating an error. You can further use $array[] = instead of array_push():

public function getList()
{
    $array = array();

    $r = mysql_query( "SELECT * FROM hobby ORDER BY hobby_name ASC" );

    while( $ro = mysql_fetch_object( $r ) )
    {
            $array[] = $ro;
    }
    return $array;
}
soulmerge
A: 
$r = mysql_query("SELECT * FROM hobby ORDER BY hobby_name ASC");
return mysql_num_rows($r) > 0 ? return mysql_fetch_array($r) : false;
AlyxVF
Noooo. That's **horrendous**.
Fragsworth
Maybe I'm wrong, but, with this, the function would only return 1 row as an array, and not an array of all row as objects ;; also, having return twice in the ?: looks strange (it will actually apparently get you a Parse error: syntax error, unexpected T_RETURN )
Pascal MARTIN