Romain Caron February 2016

PHP Array into array - error

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);
}

Answers


Gwendal February 2016

$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.

Post Status

Asked in February 2016
Viewed 1,406 times
Voted 7
Answered 1 times

Search




Leave an answer