开发者

Array as session variable

Is it possible to make an array a session variable in PHP?

The situation is that I have a table (page 1) with some cells having a link to a particular page. The next page will have a list of names (page 2, which I want to keep in a session array) with their respective checkboxes. On submitting this form, it will lead to a transaction page (page 3, where values of posted checkboxes are kept in a database for corresponding names). Now, if I return to the first page and cli开发者_运维问答ck another cell, will the session array contain the new list of names or the old ones?


Yes, PHP supports arrays as session variables. See this page for an example.

As for your second question: once you set the session variable, it will remain the same until you either change it or unset it. So if the 3rd page doesn't change the session variable, it will stay the same until the 2nd page changes it again.


Yes, you can put arrays in sessions, example:

$_SESSION['name_here'] = $your_array;

Now you can use the $_SESSION['name_here'] on any page you want but make sure that you put the session_start() line before using any session functions, so you code should look something like this:

 session_start();
 $_SESSION['name_here'] = $your_array;

Possible Example:

 session_start();
 $_SESSION['name_here'] = $_POST;

Now you can get field values on any page like this:

 echo $_SESSION['name_here']['field_name'];

As for the second part of your question, the session variables remain there unless you assign different array data:

 $_SESSION['name_here'] = $your_array;

Session life time is set into php.ini file.

More Info Here


<?php // PHP part
    session_start();          // Start the session
    $_SESSION['student']=array(); // Makes the session an array
    $student_name=$_POST['student_name']; //student_name form field name
    $student_city=$_POST['city_id'];   //city_id form field name
    array_push($_SESSION['student'],$student_name,$student_city);   
    //print_r($_SESSION['student']);
?>

<table class="table">     <!-- HTML Part (optional) -->
    <tr>
      <th>Name</th>
      <th>City</th>
    </tr>
                                                        
    <tr>
     <?php for($i = 0 ; $i < count($_SESSION['student']) ; $i++) {
     echo '<td>'.$_SESSION['student'][$i].'</td>';
     }  ?>
    </tr>
</table>


First change the array to a string by using implode() function. For Ex :

$number = array(1,2,3,4,5);

# Implode into a string using | as the separator.
$stringofnumber = implode('|', $number);

# Pass the string to a session. e.g
$_SESSION['string'] = $stringofnumber;

So when you go to the page where you want to use the array, just explode your string. For Ex :

# Required before $_SESSION can be accessed.
session_start();

# Explode back to an array using | as the needle.
$number=explode('|', $_SESSION['string']);

You array is now the value of $number.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜