Home > Mobile >  Sort foreach results by html form input order
Sort foreach results by html form input order

Time:12-09

I have an html form that posts the content of an <input> field. This field accepts one or more values. If more than one value, then the user just separates with a blank space.

Question: How can I sort the results by the exact order of the user input?

E.g.

        <form>
           <input type="text" id="name" name="name">
           <button type="submit"></button>
        </form>

User inputs the following by this specific order: bravo alpha delta charlie

After posting the form, a php foreach is run and echo's the result back to the page. The result should be sorted by:

  • bravo (results for bravo)
  • alpha (results for alpha)
  • delta (results for delta)
  • charlie (results for charlie)

I understand that I can use several php sort(); options (e.g. alphabetically), but I'm looking to sort exactly by the order that the user has input. How can I accomplish this?

Thanks

CodePudding user response:

You can use explode function from PHP like below. Explode will break the string into the same order as user entered no need apply any sort functions until a need

<?php
// user input $_POST['specific_input_name']/$_GET['specific_input_name']
$str = "bravo alpha delta charlie";

// explode with spaces
$aStr = explode(" ",$str);

// loop individual item
foreach($aStr as $value) {
    echo $value."(results for ${value})<br />";
}

// more detailed array structure
// print_r (explode(" ",$str));
?> 
  • Related