Add data in array () in PHP

I am developing a cart in PHP, however, when adding items to array, I am not succeeding, I tried as follows:

if($this->session->userdata('cart')==true){
    if(count($this->session->userdata('cart'))==0){
        $i = 0;
    } else {
        $i = count($this->session->userdata('cart'))+1;
    } 
    foreach($this->session->userdata('cart') as $value){
        $data[$i] = array(
            'cart_type' => ($this->input->post('stock_unity_push')) ? 'purchase' : 'order',
            'product_id' => $this->input->post('product_id'),
            'stock_purchase' => $this->input->post('stock_purchase'),
            'stock_unity_push' => ($this->input->post('stock_unity_push')) ? $this->input->post('stock_unity_push') : '0',
            'supplier' => $this->input->post('supplier'),
        );
        $i++;
    }
} else {
    $data[] = array(
        'cart_type' => ($this->input->post('stock_unity_push')) ? 'purchase' : 'order',
        'product_id' => $this->input->post('product_id'),
        'stock_purchase' => $this->input->post('stock_purchase'),
        'stock_unity_push' => ($this->input->post('stock_unity_push')) ? $this->input->post('stock_unity_push') : '0',
        'supplier' => $this->input->post('supplier'),
    );
}

The problem is that every time I include a new item in the array, it replaces, and does not add. How can I just add items?

Note: I'm using codeigniter to render.

Author: Sr. André Baill, 2018-12-10

2 answers

Andre, from what I understand you want to add elements to the end of the vector and the way you are doing you overwrite the array.To add elements to the end of the vector there is the method push .

 4
Author: Lucas Almeida, 2018-12-10 23:13:46

Instead of recreating array just use array_push(), so you will be sure that new elements will be added.

array_push($data, array('cart_type' => ($this->input->post('stock_unity_push')) ? 'purchase' : 'order',
                  'product_id' => $this->input->post('product_id'),
                  'stock_purchase' => $this->input->post('stock_purchase'),
                  'stock_unity_push' => ($this->input->post('stock_unity_push')) ? $this->input->post('stock_unity_push') : '0',
                  'supplier' => $this->input->post('supplier')));

Useful Links: array_push

 2
Author: 8biT, 2018-12-10 19:47:41