I know $_SESSION
is a global variable but I don't 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.
How can I list out all the product names separating by a ,
?
I have already tried using the implode()
function.
Finally, I got the answer to my query with the help of @Christophe Ferreboeuf. However, some modification was still needed.
Here's the corrected code:
$allProductName = '';
$prefix = '';
foreach ($_SESSION["cart_products"] as $cart_itm)
{
$allProductName .= $prefix . '"' . $cart_itm["product_name"]. '"';
$prefix = ', ';
}
echo $allProductName;