galvin Posted April 8, 2009 Share Posted April 8, 2009 I have checkbox options in a form that are put into "projectarray[]". I found the following code online and it does what I want when I echo $projectarray later on (simply lists out each item in the array). But I can't understand exactly what the code is doing (I get so confused with the $key and $value stuff). Like I said, it does what I want, but I really want to understand WHY. If someone has a few minutes to help me learn, could you maybe just use plain english comment above each line of code explaining what is happening? foreach ($_POST['project'] as $key=>$value) { if (is_array($value)) { for ($i = 0; $i < count($value); $i++) { $projectarray = " ".$key."[".$i."] = ".$value[$i]."\n"; } } else { $projectarray .="$value, "; } } Quote Link to comment Share on other sites More sharing options...
xtopolis Posted April 8, 2009 Share Posted April 8, 2009 I commented below my lines: foreach ($_POST['project'] as $key=>$value) { //for every element in the associative array stored in $_POST['project'], found by $key and evaluated to $value // (meaning, I look up $_POST['project'] which contains an array, the elements in there named $key have a matching $value //where $key is just the name of the next element in the array if (is_array($value)) { // if the $value that is retrieved happens to be an array itself for ($i = 0; $i < count($value); $i++) { //loop through from 0->the size of that array ($value) $projectarray = " ".$key."[".$i."] = ".$value[$i]."\n"; //append to the string $projectarray the values of the $value array.. }//end of for loop if $value is an array itself } else { //if ($value from the primary array is just a value and not an array $projectarray .="$value, "; //append the value of $value to the string $projectarray }//end of $value is not an array }//end of foreach likely to output something like: cat,dog, horse[1] = 1 horse[2] = 3 horse[3] = 4 bird, chicken *That should be fairly accurate, but I do make mistakes. If you're still confused, post an example array and I'll translate the output of your function so you can see what parts are manipulated where in the function. Quote Link to comment Share on other sites More sharing options...
galvin Posted April 8, 2009 Author Share Posted April 8, 2009 Thanks so much, xtopolis, that helps a lot. The part where it was checking to see if a value in the primary array was also an array itself was what I was not understanding. Thanks to your comments, it makes perfect sense now. For my purposes, none of the values in my primary array will ever be an array (they will all be just a value), so I could even take out that part of the code. Thanks again! Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.