Isaac Perez
Isaac Perez

Reputation: 590

Setting an array as a session variable in PHP and then accessing it

If I have an array:

$resultArr = pg_fetch_array($result,NULL);

and at the top of my php code I declare:

$_SESSION['resultArr'] = $resultArr;

Why can't I access the array elements like so:

for($i = 0; $i < $NUM_COLUMNS; $i++){
    // creation of the table and row are handled elsewhere.
    // The table is also within a <form> if that matters
    echo "<td>" .$_SESSION['resultArr'][$i]."</td>";
}

My table ends up having empty columns and I can't figure out why...

EDIT: I figured it out. I was declaring $_SESSION['resultArr'] = $resultArr; at the top of my code (right after session_start()) and it wasn't getting set. I moved it down to the point right after $resultArr = pg_fetch_array($result,NULL);

Is this how it's supposed to work or should it have worked fine at the top of the code?

Upvotes: 0

Views: 100

Answers (2)

Neil
Neil

Reputation: 400

after your edit, yes this is how it is supposed to work, you first need to declare $resultArr, then put it's value in the session array

beacause in php you are no longer working with pointers, $_SESSION['resultArr'] = $resultArr; mean "$_SESSION['resultArr'] takes all the values of $resultArr at that precise moment", but it does not mean "they are thesame, if one changes, then the other changes too" .

Upvotes: 0

Stefano Sanfilippo
Stefano Sanfilippo

Reputation: 33046

Maybe you did and didn't mention, but you must call session_start() before any operation on $_SESSION

Upvotes: 1

Related Questions