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
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

Link to comment
Share on other sites

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.)

Link to comment
Share on other sites

I have found the problem! The values were empty because I forgot to fetch the result mysql row  ;D!

 

Sry for bothering you! Next time I will pay more attention!  ???

 

Any code from above works just fine!  :P Thank you for your help and sorry again :D !

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.