Heidel Heidel - 6 months ago 20
PHP Question

php save array of values

I need to save last 10 viewed products in

$_SESSION
, so I try to use code below, but in this case
$_SESSION['lastViewedProductsList']
keeps only last
$product


$title = $node->title;
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$img = $node->uc_product_image['und'][0]['filename'];
$product = array('title' => $title, 'url' => $url, 'img' => $img);

if (!isset($_SESSION['lastViewedProductsList'])) {
$_SESSION['lastViewedProductsList'] = $product;
} else {
$_SESSION['lastViewedProductsList'] = $product;
}


How to save last 10 products?

Answer
$title = $node->title;
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; 
$img = $node->uc_product_image['und'][0]['filename'];
$product = array('title' => $title, 'url' => $url, 'img' => $img);

if (!isset($_SESSION['lastViewedProductsList'])) {
    // If the SESSION parameter does not exists, we create it as an array
    $products = array($product);
} else {
    // Else, we add the product in it
    $products = $_SESSION['lastViewedProductsList'];
    $products[] = $product;
    // We check if the array has more than 10 rows
    if(count($products) > 10){
        // If that's the case, we remove the first line in it to keep 10 rows in it
        array_shift($products);
    }
}

$_SESSION['lastViewedProductsList'] = $products;

If you want to check if the product is already in the array, check this solution: PHP: Check if value and key exist in multidimensional array