如果设置变量,如何循环遍历会话变量并设置新变量

时间:2015-02-05 04:43:54

标签: php loops foreach session-variables increment

基本上我想检查是否设置了数字,如果没有设置,设置它,否则递增数字并设置递增的数字,如果设置了最大数字(12),则退出并抛出错误。逻辑似乎打败了我。

"if is not set *number*, set it;
stop the loop;
else;"

if is set and not empty, number++; 
set the new incremented number;
stop the loop;"

如何继续循环到达三,我被困在两个。 "

<?php 
session_start();
//session_destroy();
//exit;


    //////////check if last channel is set//////

if (isset($_SESSION['channel12']) && !empty($_SESSION['channel12'])){
        echo 'You have reached maximum channels for this package';
    } else {
$channels = range(1,12);
$number=0;      

foreach($channels as $channel){
    //$number++;
    $new_channel = $channel + 1;//$number;


    ///////////////Try the first channel and if not set use it/////////
    if (!isset($_SESSION['channel'.$channel.''])){
                    $_SESSION['channel'.$channel.''] = 'channel'.$channel;
                    var_dump($_SESSION);
                break;
                ///////////////Else try next channel/////////
                } else if (isset($_SESSION['channel'.$channel.'']) && !empty($_SESSION['channel'.$channel.''])) {
                    $_SESSION['channel'.$new_channel.''] = $new_channel;
                    var_dump($_SESSION);
                    break;
                    } else {

                        }
}
    }
?>

感谢。

1 个答案:

答案 0 :(得分:2)

试试这个

<?php
session_start();

//////////check if last channel is set//////
if (isset($_SESSION['channel12']) && !empty($_SESSION['channel12'])) {
    echo 'You have reached maximum channels for this package';

} else {
    $channels = range(1, 12);
    $number = 0;

    foreach ($channels as $channel) {
        $new_channel = $channel + 1;
        //$number;

        ///////////////Try the first channel and if not set use it/////////
        if (!isset($_SESSION['channel' . $channel . ''])) {
            $_SESSION['channel' . $channel . ''] = 'channel' . $channel;
            var_dump($_SESSION);
            break;
            ///////////////Else try next channel/////////
        }
    }
}
?>