Search code examples
phpdrop-down-menu

PHP get dropdown value and text


<select id="animal" name="animal">                      
<option value="0">--Select Animal--</option>
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Cow</option>
</select>

if($_POST['submit'])
{
$animal=$_POST['animal'];
}

I have a dropdown like this. What I want, I want to get selected value and text in button submit using PHP. I mean if it's selected 1st one. I want to get both 1 and Cat


Solution

  • $animals = array('--Select Animal--', 'Cat', 'Dog', 'Cow');
    $selected_key = $_POST['animal'];
    $selected_val = $animals[$_POST['animal']];
    

    Use your $animals list to generate your dropdown list; you now can get the key & the value of that key.