Page 1 of 1

Multi select boxes

Posted: Fri Jul 26, 2002 11:20 am
by jdboyer
Can someone tell me if there is a way to count the number of items selected from a multi select box? I need to run a loop but need to know how many items have been selected by the user. Can this be done?

Posted: Fri Jul 26, 2002 12:46 pm
by RandomEngy
I was curious and did a little test about this, so I made a multiple select box with a few items, gave the data via post to a script which did var_dump($_POST) . It seemed to only hold the value which was furthest down the list, even with multiple selected. :(

Posted: Fri Jul 26, 2002 12:57 pm
by jdboyer
Actually, I just figured it out. You need to name your list box: name[] This will make it an array. Then in your PHP code you use a for loop to go through the array to access each value. My problem was that I only needed it to run through the array as many times as the number of items selected. The solution to this is to use the PHP function sizeof($arrayname) in your for loop. This returns the the size of the array which is exactly the number of selected items.

:P

Posted: Fri Jul 26, 2002 1:03 pm
by daemorhedron
The problem you have is that you are treating the select as a var instead of an array in your html select (ie <select multiple name="foo">). Try <select multiple name="foo[]"> and var_dump that. See the example code.

Code: Select all

<? if ($mselect1) var_dump($mselect1); ?>
<form method="post" action="<?=$PHP_SELF?>">
<select multiple name="mselect1&#1111;]">
<option value="r">Red</option>
<option value="g">Green</option>
<option value="b">Blue</option>
</select>
<input type=submit>
</form>
HTH!

Posted: Fri Jul 26, 2002 1:04 pm
by daemorhedron
DOH! Took me too long to type it out. =) I'll leave it to help others. =)

Posted: Fri Jul 26, 2002 1:17 pm
by jdboyer
Thanks for the help anyway.

:D