Dan Dan - 4 months ago 10
PHP Question

echo out $_SESSION data

I have a bunch of data in an array which has been collected in a session. I am able to print_r this and show all the contents but I am struggling to show the product name, id, image etc.

I am showing the using:

<?php
echo '<pre>';
print_r($_SESSION);
echo '</pre>';
?>


It prints out everything I need but not in the format I require. So I know it is collecting my data and storing it in the array. I have set the data in another files like so:

if (isset($_POST['Submit'])) {
$_SESSION['product_img'][] = $_POST['product_img'];
$_SESSION['product_id'][] = $_POST['product_id'];
$_SESSION['product_name'][] = $_POST['product_name'];
$_SESSION['product_price'][] = $_POST['product_price'];
$_SESSION['product_sku'][] = $_POST['product_sku'];
$_SESSION['product_description'][] = $_POST['product_description'];
}


And it is all of the above I want to output.

Answer

**Either you stick with your proposal : $_SESSION['...'][] **

if (isset($_POST['Submit'])) { 
    $_SESSION['product_img'][] = $_POST['product_img'];
    $_SESSION['product_id'][] = $_POST['product_id'];
    $_SESSION['product_name'][] = $_POST['product_name'];
    $_SESSION['product_price'][] = $_POST['product_price'];
    $_SESSION['product_sku'][] = $_POST['product_sku'];
    $_SESSION['product_description'][] = $_POST['product_description'];
} 

and format it like so:

foreach($_SESSION as $elements)
{
    foreach($elements as $element) {
        echo $element . '<br />';
    }
}

Or use this other method:

if (isset($_POST['Submit'])) { 
    $_SESSION['product_img'] = $_POST['product_img'];
    $_SESSION['product_id'] = $_POST['product_id'];
    $_SESSION['product_name'] = $_POST['product_name'];
    $_SESSION['product_price'] = $_POST['product_price'];
    $_SESSION['product_sku'] = $_POST['product_sku'];
    $_SESSION['product_description'] = $_POST['product_description'];
} 

and format it like so:

foreach($_SESSION as $element)
{
    echo $element . '<br />';
}