Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Array Values from Form

Status
Not open for further replies.

PCHomepage

Programmer
Feb 24, 2009
609
US
In trying to select multiple values from a form drop down (select) list, I am not sure how to use the results.

For example, the code below gives me a comma-separated list but it also puts a comma at the end that causes issues.

Code:
if(!empty($_POST['Clinic'])) {
	if (is_array($_POST['Clinic'])) {
		foreach($_POST['Clinic'] as $key => $val) {
			echo $val. ",";
		}
	}
}

However, I need the results to be as a string variable but when I try the following, it gives only the last value. I am quite rusty in PHP so can anyone help get me going?

Code:
if(!empty($_POST['Clinic'])) {
	if (is_array($_POST['Clinic'])) {
		foreach($_POST['Clinic'] as $key => $val) {
			$GetClinic = $val;
		}
	}
}

Thanks!
 
Your loops do 2 completely different things. One outputs to screen as it runs the foreach loop, the second one simply overwrites the variable each time it runs. so at the end you get the last value.

The easy way, use the implode function.

No need for a loop, it does it in a single line.

Code:
$mystring=implode(",",$_POST['Clinic']);


The slightly harder way, concatenate each item with a comma and then remove the last comma from the string:

Code:
foreach(...){
$myvar[COLOR=red yellow].[/color]=$val . ",";
}

And then remove  the last comma:
$myvar=substr($myvar,0,strlen(myvar)-1);


----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Behind the Web, Tips and Tricks for Web Development.
 
Great, thanks! I knew what was happening but I wasn't sure what to do about it. The latter is what I was trying to remember (I knew had to do with a dot) but the former is what I used because it's clearly simpler.

I appreciate the help.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top