Adictonator Adictonator - 5 months ago 13
PHP Question

php - Retrieve value from $_SESSION and output using another variable

My question might seem totally silly but I am really stuck here.

I know $_SESSION is a global variable but I can't seem to know how to retrieve the value it stores.

For example:

<?php
if(isset($_SESSION["cart_products"]))
{
foreach ($_SESSION["cart_products"] as $cart_itm)
{
//set variables to use in content below
$product_name = $cart_itm["product_name"];
$product_code = $cart_itm["product_code"];

echo '<p>'.$product_name.'</p>';
echo '<p><input type="checkbox" name="remove_code[]" value="'.$product_code.'" /></p>';
}
}

echo $_SESSION["cart_products"];
?>


Here you can see, the
$_SESSION["cart_products"]
holds some value (information like product name, product code etc). Now, the problem is that I just want to echo out all the product names that are stored in
$_SESSION["cart_products"]
.

Since it's a cart list, it contains more than ONE product details. But, when I echo out
$product_name
, it only shows the name of the last product in the list. And echoing out
$_SESSION["cart_products"]
gives
array to string
error.

Please, tell me how can I list out all the product names separating by a
,
.

Any help will be greatly appreciated.
Thanks in advanced.

PS: I have already tried using
implode()
function.

Answer

for displaying all the product name separated by , use this code.

$allProductName = '';
 $prefix = '';
 foreach ($_SESSION["cart_products"] as $cart_itm)
{
    $allProductName .= $prefix . '"' . $product_name. '"';
    $prefix = ', ';
}
echo $allProductName;