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?

stergosz
  • 5,754
  • 13
  • 62
  • 133
  • 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. – kapa Feb 23 '12 at 09:26
  • your solution is faster, with array_push you will call functions, this is a overhead.... see at http://php.net/manual/de/function.array-push.php – silly Feb 23 '12 at 09:28

4 Answers4

3

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

Yes. That's the way to do it.

Andrei G
  • 1,590
  • 8
  • 13
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.

hsz
  • 148,279
  • 62
  • 259
  • 315
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

Nicola Peluchetti
  • 76,206
  • 31
  • 145
  • 192
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.

halfer
  • 19,824
  • 17
  • 99
  • 186
Nishant
  • 3,614
  • 1
  • 20
  • 26