如何循环会话变量并设置新变量(如果已设置)

How to loop over session variables and set new ones if they are set

基本上我想检查是否设置了一个数字,如果没有设置,设置它,否则增加数字并设置增加的数字,如果设置了最大数字(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 {

                        }
}
    }
?>

谢谢。

试试这个

<?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/////////
        }
    }
}
?>