0

I have the following code:

if(isset($_SESSION["spgrund"])) {
    $spgrund = $_SESSION["spgrund"];
}else{
    $spgrund = '';
}

This code is repeated about 20 times for each session variable. How can I make a loop out of it?

foreach($_SESSION as $key => $value){
    $$key = $value;
}

I think that should work. But I get undefined variable error messages. Can't I use such a loop?

2
  • what's the error message exactly ? which line? Commented Jan 2, 2012 at 10:46
  • The line comes from my script below. Therein I have echo and some if ($spgrund == "1"). Commented Jan 2, 2012 at 10:48

2 Answers 2

3

What you actually try to achieve is already available in PHP, the extract­Docs function:

extract($_SESSION);

From it's documentation:

Import variables from an array into the current symbol table.

Checks each key to see whether it has a valid variable name. It also checks for collisions with existing variables in the symbol table.

You would still need look for undefined variables however. Probably you should define them first?

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

4 Comments

If I first use $spgrund=''; and then extract it takes the first defined empty value...
That is because spgrund is not a key of $_SESSION. Use var_dump($_SESSION) to look what's inside that variable. This probably helps you.
It is in the session (print_r ($_SESSION);). Also used var_dump and it prints &string(4) "test". But echo is empty ...
If I comment out $spgrund=''; than it works, but I get undefined variable errors. Now more about my code: I have a form which sends to form_do.php. Therein all POST Parameters are set into SESSION variables and I make a redirect to form.php, which was calling form_do.php. I think I have to leave the old way because I spent to much time on improving this ...
0
foreach($_SESSION as $key => $value)
{
    $$key = $value;
}

you missed the $ for value

1 Comment

Thanks! I had a typo here, but already corrected in my script. The problem is that some variables are not set, but there are some if which seems to need it. Is there a way to optimize the code (20 times the same code) within a foreach?

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.