Re: parsing select multiple="multiple"

From: Date: Tue, 19 Feb 2013 21:06:04 +0000
Subject: Re: parsing select multiple="multiple"
References: 1 2 3 4 5  Groups: php.general 
Request: Send a blank email to php-general+get-320246@lists.php.net to get a copy of this message
On 2/19/2013 2:02 PM, John Taylor-Johnston wrote:
tamouse mailing lists wrote: I hate arrays. :D
Here's a small snippet showing how it works, I hope: foreach ($DPRpriority as $item => $value) { echo "<li> ".$item.": ".$value['name']." selected: ".$value['selected']." </li>\n"; }
Question 1: when did we have to add [] to a <input> name to turn it into an array? <input type="checkbox" name="DPRlocationdetails[]" value="Unknown"> According to phpinfo() it still comes out as $_POST['DPRlocationdetails'] without []. Are the [] necessary? ---------------------------------------------- Question 2: I was looking at some code in the Manual, where someone used isset and is_array. How necessary is if(isset($_POST['DPRlocationdetails'])) and then to use: if(is_array($_POST['DPRlocationdetails'])) That seems like over kill? ---------------------------------------------- Question 3: My code works, perfectly. In this case, I decided to attack some check-boxes first. The resulting function will work for <select multiple> too.. Does anyone see me doing something wrong in my code below? My questions are: Is this the only way to pass "Unknown", "Family Home" or "Apartment" into the function? Is this correct? ---- if ($_POST['DPRlocationdetails'] == "Unknown") Somebody once told me I had to do it this way? ---- if ("Unknown" == $_POST['DPRlocationdetails']) John --------------------snip--------------------------- <form action="foo.php" id="DPRform" method="post"><input value="Update" type="submit"> <input type="checkbox" name="DPRlocationdetails[]" value="Unknown" <?php filter_value($_POST['DPRlocationdetails'],"Unknown"); ?>> Unknown <input type="checkbox" name="DPRlocationdetails[]" value="Family Home" <?php filter_value($_POST['DPRlocationdetails'],"Family Home"); ?>> Family Home <input type="checkbox" name="DPRlocationdetails[]" value="Apartment" <?php filter_value($_POST['DPRlocationdetails'],"Apartment"); ?>> Apartment </form> <?php function filter_value($tofilter,$tofind) { foreach($tofilter as $value){
     if ($value == $tofind) echo "checked";
     }
} ?> The [] are necessary if there are going to be multiple occurrences of an input with the same name, hence the [] to allow your php script to extract all of the occurrences.
Using isset and is_array comes in handy to help you handle the incoming var properly. If it IS set, you then have to check if there is only one value (hence a string) or if there are multiple values (an array). #3 - no idea what you are asking.

« previous php.general (#320246) next »