-4

I want to add new array item to an existing array. I'm using array_push for this purpose but it is not working.

Array

Array ( [productID] => 51  )

Php Code

if(isset($_REQUEST['sendProductId'])){

    $inserted = $_COOKIE['productID'];
    $original = $_REQUEST['sendProductId'];

    if($inserted){
        $cookie_value   =   array_push( $inserted, $original ); 
    }else{
        $cookie_value = $_REQUEST['sendProductId'];
    }
    $cookie_name = 'productID';

    setcookie($cookie_name, $cookie_value, time() + (86400 * 30));

}
print_r($_COOKIE);

Actually I want to add products ids into a cookie. I have also used array_splice for this but it's also not working.

Please guide me where I'm going wrong.

Jonnus
  • 2,988
  • 2
  • 24
  • 33
Ayaz Ali Shah
  • 634
  • 2
  • 7
  • 16

2 Answers2

-1

With serialize(array()) set array to cookie and for read data use $data = unserialize($_COOKIE[$cookie_name]);

so try this

if(isset($_REQUEST['sendProductId'])){

    $inserted = 51;//$_COOKIE['productID'];
    $original = 52;//$_REQUEST['sendProductId'];

    $cookie_name = 'productID';

    $cookie_value[0]   = $original;   
    if($inserted)
        $cookie_value[1]   = $inserted;   



    setcookie($cookie_name, serialize($cookie_value), time() + (86400 * 30));

}

$data = unserialize($_COOKIE[$cookie_name]);
array(2) {
  [0]=>
  int(52)
  [1]=>
  int(51)
}
ashkufaraz
  • 5,179
  • 6
  • 51
  • 82
-3

From the documentation for array_push():

array_push — Push one or more elements onto the end of array

int array_push ( array &$array , mixed $value1 [, mixed $... ] )

array_push() treats array as a stack, and pushes the passed variables onto the end of array. The length of array increases by the number of variables pushed. Has the same effect as:

<?php
$array[] = $var;
?>

repeated for each passed value.

ryanyuyu
  • 6,366
  • 10
  • 48
  • 53