PHP checkboxes in sequentially ordered

–2 votes
asked Sep 12, 2017 by axai
<form method="post" action=""> <input type="checkbox" name="boxes[]" value="alpha">alpha</input> <input type="checkbox" name="boxes[]" value="beta">beta</input> <input type="checkbox" name="boxes[]" value="omega">omega</input> <input type="submit" name ="submit" value="submit">
</form>

In this form, How can i get the array values order by picks?

For example If i went to pick beta>omega>alpha the array would be ['beta', 'omega', 'alpha']

instead of ['alpha', 'beta', 'omega']

Then after calling it in PHP

if(isset($_GET['submit'])){ $boxes = $_GET['boxes']; //HERE IS MY 2ND PROBLEM
}

What i'm trying to do at //HERE IS MY 2ND PROBLEM is echoing each name order as the array, for example

the ['beta', 'omega', 'alpha'] would be like

echo 'b'; echo 'o'; echo 'a';

as ordered in the array.

So how exactly can i do that?

1 Answer

+2 votes
answered Mar 16, 2018 by alex-macarthur

Because all of that form information is sent at once at submission, there's no way to get the order they were selected without using JavaScript.

If you wanted, you could record the checkbox selections with JS, store the keys to a separate array or list, and then pass that array with a hidden field.

 <form method="post" action=""> <input type="checkbox" name="boxes[]" value="alpha">alpha</input> <input type="checkbox" name="boxes[]" value="beta">beta</input> <input type="checkbox" name="boxes[]" value="omega">omega</input> <!-- Update this field dynamically with JavaScript. --> <input type="hidden" name="checkboxOrder" value="" /> <input type="submit" name ="submit" value="submit"> </form>

It might get sticky if users uncheck boxes after checking, but regardless, that's the way I'd probably approach the problem.

Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
...