stergosz
stergosz

Reputation: 5860

php add key with value to array faster way

I have an array:

    $data = array(
        'loggedin' => false
    );

i want to add other keys as well their values if the user is logged in so i use:

    if ( $this->auth_model->loggedin()){//user is logged in
        $data["loggedin"] = true;//set to true
        $data["user_id"] = $this->session->userdata["uid"];//add new key with its value on $data array
    }

is this the best way to do it or should i use array_push and such?

Upvotes: 2

Views: 4661

Answers (4)

Nishant
Nishant

Reputation: 3694

The way you are adding is better than using array_push (reason: you are inserting few values and it avoid the overhead of calling a function) if you are adding more values to this array, then you can use array_push.

Upvotes: 1

Andrei G
Andrei G

Reputation: 1590

No need to add overhead by calling a function (like array_push).

Yes. That's the way to do it.

Upvotes: 3

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76880

i don't think you can use array_push to add values to an associative array, so it's ok to do as you are doing

Upvotes: 2

hsz
hsz

Reputation: 152226

With array_push you cannot set the key.

The way you have described is the fastest one.

You can create a second array with user_id key and then merge those two arrays, but this is not a good way to solve this case.

Stay with that you have right now.

Upvotes: 2

Related Questions