Validate and submit multiple input fields in array in PHP: rank order

后端 未结 1 1118
死守一世寂寞
死守一世寂寞 2021-01-28 04:06

I am using PHP to generate an HTML form for a ranking task, in order to obtain the rank order that the user assigns to a list of alternatives. The generated form is presented as

1条回答
  •  孤城傲影
    2021-01-28 04:40

    I figured out a simple solution that compares the $_POST array against a pre-specified array of accepted values, based on this.

    The validation code:

    $rankErr = "";
    $hasErrors = false;
    
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $rank = $_POST['rank_'];
    $matchArray = array(1,2,3,4);
        if(is_array($rank) && is_array($matchArray) && array_diff($rank, $matchArray) === array_diff($matchArray, $rank)){
            $hasErrors = false;
        } else {
            $rankErr = "Please enter unique values (1-4) under Rank.";
            $hasErrors = true;
        }
        if (!$hasErrors) {
        include ("process.php"); 
        }
    }
    

    Seems to work perfectly. Hope this helps others with the same problem.

    0 讨论(0)
提交回复
热议问题