简体   繁体   中英

Add values to $_SESSION['name'] then Loop thru values

I'm using a $_SESSION variable to store error codes in an app I'm creating. On my form processing page, i'm using the following code (as an example):

session_start();
$_SESSION['site_msg']   = array();
if(1 == 1) {
    $_SESSION['site_msg'] = 18;
}
if(2 == 2) {
    $_SESSION['site_msg'] = 21;
}
if(3 == 3) {
    $_SESSION['site_msg'] = 20;
}

I'm hoping to use a function to get the values from the array to use elsewhere in my code.

function error_code() {
    foreach($_SESSION['site_msg'] as $value) {
        echo "Value: $value <br />";
    }
}

The above gives an error; Warning: Invalid argument supplied for foreach() ...

If I write the function like this:

$array[] = $_SESSION['site_msg'];
foreach($array  as $value) {
echo  "VAL: " . $value;
}

It only gives me the last value, 20.

Anyone have an idea where I went wrong? Thanks!

<?php
session_start();
$_SESSION['site_msg']   = array();
if(1 == 1) {
    array_push($_SESSION['site_msg'],18);   // '=' overwrites the data, so push data in session array not to assign
}
if(2 == 2) {
    array_push($_SESSION['site_msg'],21);
}
if(3 == 3) {
    array_push($_SESSION['site_msg'],20);
}


$array = $_SESSION['site_msg'];  //remove [] from variable, its not needed
foreach($array  as $value) {
    echo  "VAL: " . $value;
}
?>

You declare your variable $_SESSION['site_msg'] as an array, but you pass integer values to this variable! You need to add your values as new array elements.

This should work:

session_start();
$_SESSION['site_msg']   = array();
if(1 == 1) {
    $_SESSION['site_msg'][] = 18;
}
if(2 == 2) {
    $_SESSION['site_msg'][] = 21;
}
if(3 == 3) {
    $_SESSION['site_msg'][] = 20;
}

As an alternative you can use the function array_push() to add your values to the array:

session_start();
$_SESSION['site_msg']   = array();
if(1 == 1) {
    array_push($_SESSION['site_msg'], 18);
}
if(2 == 2) {
    array_push($_SESSION['site_msg'], 21);
}
if(3 == 3) {
    array_push($_SESSION['site_msg'], 20);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM