Relm
Relm

Reputation: 8272

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

Basically I want to check if a number is set, if not set, set it, else increment the number and set the incremented number, if the maximum number (12) is set, exit and throw an error. The logic seems to defeat me.

"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;"

How do I continue the loop to it gets to three, I'm stuck on two. "

<?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 {

                        }
}
    }
?>

Thanks.

Upvotes: 0

Views: 718

Answers (1)

kamlesh.bar
kamlesh.bar

Reputation: 1804

try this

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

Upvotes: 2

Related Questions