• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 244
  • Last Modified:

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?

Al
0
ragnarok89
Asked:
ragnarok89
  • 2
1 Solution
 
Ahmed MerghaniCommented:
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.
0
 
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.
http://php.net/manual/en/tutorial.forms.php
0
 
ragnarok89Author Commented:
fishboy2000sd,

   Worked like a charm; thank you.

Al
0
 
Ahmed MerghaniCommented:
You are welcome
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now