Determine selected element number

Hi All,

I have a dropdown box on a form that lists countries:

$lines =file('./Countries.csv');
foreach($lines as $data) {
   list($countriesAr[],$Continent[],$Notify[]) = explode(',',$data);

for($i=0;$i<count($countriesAr);$i++) {
     echo "<option value='".$countriesAr[$i]."'";
     if($_POST['country'] ==  $countriesAr[$i]) 
          echo "SELECTED";
     echo ">".$countriesAr[$i]."</option>\n";

Open in new window

My question is, when the form get submitted, I want to know which country was chosen, i.e. the first on the list, or 12th, etc. I need to know the element number. How do I get that value?

Who is Participating?
Ahmed MerghaniSoftware EngineerCommented:
Hi ragnarok89,

You first need to know the selected item, then get the item index from the array. It will be something like this:

$selected_item = $_POST['select'];

$index_of_value = array_search($selected_item, $countriesAr);

Open in new window

NOTE that the indexing is start form 0 the means the first element will be 0, the second element will be 1 ...etc.
Ray PaseurCommented:
Just curious - why does the number of the selection matter?  I cannot think of any design pattern that would work that way.  It's potentially very brittle - what if the number or order of the countries changed?  If you have code that depends on a numeric position in an array from an external source (like $_POST) you may be accepting too much risk.  Just a thought.
ragnarok89Author Commented:

   Worked like a charm; thank you.

Ahmed MerghaniSoftware EngineerCommented:
You are welcome
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.