Multi select boxes

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
jdboyer
Forum Newbie
Posts: 9
Joined: Wed Jul 17, 2002 3:30 pm
Location: Calgary, Alberta, Canada

Multi select boxes

Post 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?
User avatar
RandomEngy
Forum Contributor
Posts: 173
Joined: Wed Jun 26, 2002 3:24 pm
Contact:

Post 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. :(
jdboyer
Forum Newbie
Posts: 9
Joined: Wed Jul 17, 2002 3:30 pm
Location: Calgary, Alberta, Canada

Post 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
daemorhedron
Forum Commoner
Posts: 52
Joined: Tue Jul 23, 2002 11:03 am

Post 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!
daemorhedron
Forum Commoner
Posts: 52
Joined: Tue Jul 23, 2002 11:03 am

Post by daemorhedron »

DOH! Took me too long to type it out. =) I'll leave it to help others. =)
jdboyer
Forum Newbie
Posts: 9
Joined: Wed Jul 17, 2002 3:30 pm
Location: Calgary, Alberta, Canada

Post by jdboyer »

Thanks for the help anyway.

:D
Post Reply