Jump to content

retturn array without [0] index


clankill3r

Recommended Posts

Hi, i get a array like this:

 

Array

(

    [0] => Array

        (

            [id] => 108

            [twitter_id] => HelmaLodders

            [name] => Lodders, W.J.H.

            [nickname] => Helma

            [fraction] => VVD

            [residence] => Zeewolde

            [age] => 42

            [gender] => Vrouw

            [ancienniteit] => 334

            [tweets] => 0

            [following] => 0

            [followers] => 0

            [listed] => 0

        )

 

)

 

but how can i get they array without the [0]

 

Array

(

            [id] => 108

            [twitter_id] => HelmaLodders

            [name] => Lodders, W.J.H.

            [nickname] => Helma

            [fraction] => VVD

            [residence] => Zeewolde

            [age] => 42

            [gender] => Vrouw

            [ancienniteit] => 334

            [tweets] => 0

            [following] => 0

            [followers] => 0

            [listed] => 0

        )

 

here is the function that i use to get the array:

 

function getRepresentativeByID($id) {
$query = "SELECT * FROM kamerleden WHERE id='$id'";
$data = execQuery($query);
return $data;
}

 

 

I know return $data[0]; will work but my feeling is that that's kinda sloppy.

(i did something simulair else and returning something[0] gave me problems when there was nothing to return).

Link to comment
https://forums.phpfreaks.com/topic/239369-retturn-array-without-0-index/
Share on other sites

Just use $array[0].

 

In the database wrapper that I use, I have a fetch_single method for things like your query above where you know it's only going to be one result. This automatically makes my array one-dimensional.

 

EDIT: Or you could do something like this:

function getRepresentativeByID($id) {
$query = "SELECT * FROM kamerleden WHERE id='$id'";
$data = execQuery($query);

return (count($data) == 1) ? $data[0] : null;
}

thanks.

 

About fetch_single,

 

i can only find:

sqlite_fetch_single

 

You are using some sort of database class or library, so the solution exists inside it.  Along the lines of what Reddix provided you could do:

 

return is_array($data) ? $data[0] : $data;

 

This will handle cases where $data might be an error message.  When you use a wrapper library it's up to you to understand sufficiently how it works, and whether or not there is a function/method that is built to return exactly one row.

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.