Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use array_push on a SESSION array in php?

I have an array that I want on multiple pages, so I made it a SESSION array. I want to add a series of names and then on another page, I want to be able to use a foreach loop to echo out all the names in that array.

This is the session:

$_SESSION['names']

I want to add a series of names to that array using array_push like this:

array_push($_SESSION['names'],$name);

I am getting this error:

array_push() [function.array-push]: First argument should be an array

Can I use array_push to put multiple values into that array? Or perhaps there is a better, more efficient way of doing what I am trying to achieve?

like image 418
zeckdude Avatar asked Apr 11 '10 09:04

zeckdude


People also ask

How do I store multiple values in a session?

To add multiple values, you need to retrieve the session value that is already present, append the new data to it, and store the result back into session. Its up to you to decide what data structure makes sense, depending on how you want to retrieve the individual parts of data.

Can I store array in session PHP?

Using Session array to maintain data across the pages. Array can store more items or data in a single variable but these are not available in different pages for use. Any ordinary ( or normal ) array will loose its data as page execution ends.

How do you destroy a session variable?

A PHP session can be destroyed by session_destroy() function. This function does not need any argument and a single call can destroy all the session variables. If you want to destroy a single session variable then you can use unset() function to unset a session variable.

How do I print a session array?

If you want to print the full array, as a string, try print_r($array); .


1 Answers

Yes, you can. But First argument should be an array.

So, you must do it this way

$_SESSION['names'] = array();
array_push($_SESSION['names'],$name);

Personally I never use array_push as I see no sense in this function. And I just use

$_SESSION['names'][] = $name;
like image 171
Your Common Sense Avatar answered Sep 30 '22 02:09

Your Common Sense