Search code examples
phpcheckboxechoranking

How to rank (prioritize) values from numbered checkbox form in PHP


I am using the code below to ask users to rank which programming language they are more comfortable with. The users need to rank from 1-3 (1 being the one they are most comfortable with)

<form id="form1" name="form1" method="post" action="">
<input type="number" name="php" required="required" max="3" min="1"/>PHP     <br />
<input type="number" name="python" required="required" max="3" min="1"/>Python <br />
<input type="number" name="ruby" required="required" max="3" min="1"/>Ruby <br /><br />
<input type="submit" name="button" id="button" value="Submit" />
</form>

Once the user prioritizes the programming languages and hits submit, how can I on the next page echo the ranking selection? (e.g. Your first choice is x, your second choice is y and your third choice is z)


Solution

  • I would do it like so (Note that I've changed the the value of the name attributes on the form elements):

    <form id="form1" name="form1" method="post" action="">
    <input type="number" name="lang[php]" required="required" max="3" min="1"/>PHP     <br />
    <input type="number" name="lang[python]" required="required" max="3" min="1"/>Python <br />
    <input type="number" name="lang[ruby]" required="required" max="3" min="1"/>Ruby <br /><br />
    <input type="submit" name="button" id="button" value="Submit" />
    </form>
    

    And in the php:

    //Get the form results (which has been converted to an associative array) from the $_POST super global
    $langs = $_POST['lang'];
    
    //Sort the values by rank and keep the key associations.
    asort($langs, SORT_NUMERIC );
    
    //Loop over the array in rank order to print out the values.
    foreach($langs as $lang => $rank)
    {
       //echo out here first, second, and third rank with each iteration respectively.
    }
    

    The asort function simply sorts the array by value while maintaining key association.