1

If I have 30 session variables and I want to do an if statement to only 10 of them.

if (empty($_SESSION['XYZ'])) {
   $_SESSION['XYZ'] = 0;
}

what should I do? Do I call an if statement after every session variables that i needed for?

5 Answers 5

1

Consider putting the names of the keys in an array and then looping through with foreach.

$keys = array('x','y','z');
foreach ($keys as $key)
{
    if (empty($_SESSION[$key])
    {
        // do stuff
    }
}

An advantage is you can quickly add or remove keys to check.

Sign up to request clarification or add additional context in comments.

Comments

1
$vars = array('XYZ','ABC','DEF');

foreach($vars as $i){
  if(empty($_SESSION[$i])) $_SESSION[$i] = 0;
}

[edit]
I like how we have the same answer 4 times now, and counting!

Comments

0

If they are in series, that is, from 0 to 29 then you can use a loop to traverse them!

Comments

0

Something like so?

$keys = array("A", "B", "C", "D", "E", "F");
foreach ($keys as $key) {
    if (empty($_SESSION[$key])) {
        $_SESSION[$key] = 0;
    }
}

Comments

0

You could list the keys you want to zero-out in an array and set them as follows:

$keys = array('XYZ','FOO','BAR');

foreach ($keys as $key) {
  if (empty($_SESSION[$key])) {
    $_SESSION[$key] = 0;
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.