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
https://forums.phpfreaks.com/topic/65824-please-explain-this-code-snippet/
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;

$_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 :)

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.