Explain this snippet of code

I’m not following the following snippet of code. Can someone please elaborate for me (hopefully step by step)? Trouble areas are bolded.

foreach ( $array [B]as [/B][B]$key=>$type[/B])
{
  if (empty($_GET[[B]$key[/B]]))
  {
  [B]${$key} = NULL;[/B]
  continue;
}

What I am having trouble with here. I can use foreach statements, and do, but they I don’t really understand them. For example, why is “as” needed and what does it represent?

I often see the variable $key used. I was wondering what the concept is behind the use of “$key.” I guess it is supposed to represent something, but what?

In $key=>$type, what does the “=>” represent and do?

And finally, ${$key} = NULL; is totally opaque to me. I know it is setting something to null, and $key looks like a variable, but why is it surrounded in curly braces, with yet another $ sign preceding it?

I’ve been to the php manual but the foreach section wasn’t very clear to me. (It also uses $key to represent the argument after the as statement in a foreach.)

These are all pretty newbie questions, so all clarity is appreciated. :slight_smile:

Let’s say you have this code:

<?php

$myArray = array(5,6,7,8);

foreach($myArray as $k => $v){
    echo 'array index: '.$k.' = '.$v.'<br />';
}

?>

The foreach statement translates roughly as saying:

For each element in the array $myArray store the array index as $k and the array value for that index as $v and then do what is between the {}.

So the output of the above echos will be:


array index: 0 = 5
array index: 1 = 6
array index: 2 = 7
array index: 3 = 8


This is not the entire foreach loop. There’s a closing bracket missing.

It creates a variable with name $key and value NULL.
For example, if $key = ‘apple’, then ${$key} will create the variable $apple.
In the rest of your script, when you use the variable $apple, it will exist and have the value NULL.

Thanks so much both of you - and sorry for the typos in the OP. I went through several phrasings for clarity but just accumulated typos.