I'm trying to create a simple function to return only the first set of results from a query but I'm getting the following error:
Parse error: syntax error, unexpected '[' in /Users/MAMP_SITES/website/classes/DB.php on line 78
Here is the code that causes the error:
$user = DB::getInstance()->get('users', array('username', '=', 'rich'));
if(!$user->count()) {
echo 'No user';
} else {
foreach($user->results() as $user) {
echo $user->first()->username;
}
}
Here are the relevant functions from DB.php:
public function results() {
return $this->_results;
}
public function first() {
return $this->results()[0]; // This is line 78 where the error is
}
I'm getting this code from a tutorial that may be a little out of date.
Array dereferencing is only available in more recent PHP versions. To return the first array item you can use the current() function.
return current($this->results());
You can try:
public function first() {
$results = $this->results();
return (sizeof($results)>0 ? $results[0] : null);
}
OR
public function first() {
return current( $this->results() );
}