2

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?

2
  • 2
    Well, this is how you add values to an associative array. You can't really do this with array_push(). Also, speed does not really matter when you are adding two values to an almost empty array. Don't micro-optimize. Commented Feb 23, 2012 at 9:26
  • your solution is faster, with array_push you will call functions, this is a overhead.... see at php.net/manual/de/function.array-push.php Commented Feb 23, 2012 at 9:28

4 Answers 4

3

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

Yes. That's the way to do it.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

2

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

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.