sk123
sk123

Reputation: 600

Sorting a data in php. Only variables can be passed by reference

I'm fairly new to php, i am trying to sort users in ascending order by their first and last names. I have tried this but keep getting can't pass values by reference. How can i do this

foreach( $users->result() as $user ):
            if ($user->first_name != '' && !$user->block):
                $user_list[$user->id] = sort($user->first_name . '' . $user->last_name);
            endif;
        endforeach;

Upvotes: 0

Views: 418

Answers (2)

Mark Seah
Mark Seah

Reputation: 542

You can't pass a string to the method sort(). I am assuming this is from the database, under such cases I would usually sort it using SQL first.

But nevertheless to achieve what you want.

$user_list=array();
foreach( $users->result() as $user ):
            if ($user->first_name != '' && !$user->block):
                $user_list[$user->id] = $user->first_name.' '.$user->last_name
            endif;
        endforeach;

sort($user_list);

Upvotes: 2

Alex Yu
Alex Yu

Reputation: 29

foreach( $users->result() as $user ) {
    if ($user->first_name != '' && !$user->block) {
        $user_list[$user->id] = $user->first_name . '' . $user->last_name;
    }
}

$user_list = asort($user_list); //sorted array

Upvotes: 0

Related Questions