1

I'm trying to add an array into an other array at a specific key. But I have this message :

array_push() expects parameter 1 to be array, null given

I don't understand because in the else I create the array.

$key = $this->input->get('vente');
if(array_key_exists($key,$this->session->userdata('panier'))){
    array_push($this->session->userdata('panier')[$key],$toAdd);
}else{
    $this->session->userdata('panier')[$key] = array();
    array_push($this->session->userdata('panier')[$key],$toAdd);
}
1
  • Thanks arkascha, but I want put the array at this index. Not at the end of the array. Commented Feb 8, 2016 at 20:14

1 Answer 1

1

$this->session->userdata return an array but you can't modify it directly. Try this :

<?php 
// Storing the session item in a var
$panier = $this->session->userdata('panier');

// $this->session->userdata return null when the item doesn't exist, so we have to check it
if (empty($panier)) $panier = array();

$key = $this->input->get('vente');

if( array_key_exists($key, $panier) ) {
    array_push($panier[$key], $toAdd);
} else {
    $this->session->userdata('panier')[$key] = array();
    array_push($panier[$key], $toAdd);
}

// Then, we set the var in session again !
$this->session->set_userdata('panier', $panier);

Don't hesitate if you need more explanations.

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

2 Comments

Thanks a lot Gwendal. I didn't think that I can't modify it directly. You save my night ;)
Ca me fait plaisir @RomainCaron :)

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.