Jump to content

Please explain this code snippet


tlavelle

Recommended Posts

Could someone please explain the code snippet below line by line?  I especially am interested in the last line.  Is that a multidimensional array?  How does the foreach() iterate across it?

 

Thanks

$_SESSION['Posted_values'] = array();
foreach($_POST as $fld => $val)
   $_SESSION['Posted_values'][$fld] = $val;

Link to comment
Share on other sites

It pretty straight forward:

 

$_SESSION['Posted_values'] = array();

This line just create a session variable called 'Posted_values' and assign an empty array to it.

 

foreach($_POST as $fld => $val)

This line starts a foreach() loop which takes each element in the $_POST array and each cycle in the loop it assigns the $_POST arrays key to the variable $fld and its value to $val. For example will $_POST['name'] = "Wuhtzu" become $fld = "name" and $val = "Wuhtzu".

 

$_SESSION['Posted_values'][$fld] = $val;

Here the $_SESSION['Posted_values']-array is populated with values... The above example will result in $_SESSION['Posted_values']['name'] = "Wuhtzu"

 

And yes it's a 2d-array.

 

MadTechie meant that the code you posted can be replaced with $_SESSION['Posted_values'] = $_POST;

Link to comment
Share on other sites

$_SESSION['Posted_values'] = array();
foreach($_POST as $fld => $val)
   $_SESSION['Posted_values'][$fld] = $val;

 

is the same as doing this

 

$_SESSION['Posted_values'] = $_POST;

 

which copies the $_POST array into the session 'Posted_values'

 

not sure how else to explain it!!

 

EDIT: nice one Wuhtzu :)

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.