Jump to content

[SOLVED] Array in PHP Session


eutu9

Recommended Posts

I am trying to insert an array into a PHP session

 

I tried this way:

$products[0]="product 0";

$products[1]="product 1";

$products[2]="product 2";

 

$_SESSION['products']=$products;

 

 

I tried this way:

$_SESSION['products'][0]="product 0";

so on...

 

When I am trying to acces the products:

 

foreach($_SESSION["products"] as $key=>$value)

{

    echo $key."-".$value;

}

 

all I get is:

0-

1-

2-

...

 

It doesn't writes the values! I tried to do it multiple ways!

What is my mistake?

 

How can I add an array to a session? I googled it and I can't see where is my mistake.

Maybe u can help me!

 

Thanks!

Link to comment
https://forums.phpfreaks.com/topic/82042-solved-array-in-php-session/
Share on other sites

This works... not sure exactly what you want to do, but it displays what it's supposed to..

 

<?php
session_start();
$products[] = "product 0";
$products[] = "product 1";
$products[] = "product 2";

$_SESSION['products'] = $products;

foreach ( $_SESSION['products'] as $key => $value ) {
    echo $key . ' - ' . $value . '<br>';
}
?>

 

PhREEEk

My guess is that your code is clearing the values at some point or that register globals are on and $_SESSION['products'] is getting overwritten.

 

Post your actual code.

 

Note: serialize/unserialize is not needed to store arrays in sessions (in fact the session code serializes and unserializes the data when it stores and retrieves if from the session data file.)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.