Search code examples
phpmultiple-choice

PHP: Various outcomes based on radio selections


I have this script, which works perfectly well. BUT I will end up creating hundreds of variations if I keep doing it this way.

    <?php

$q1 = $_GET["q1"];
$q2 = $_GET["q2"];
$q3 = $_GET["q3"];
$q4 = $_GET["q4"];


if ( $q1 == "a" && $q2 == "a" && $q3 == "a" && $q4 == "a" ) {
    header("Location: http://www.mostly-a.co.uk");
    exit;    
}

if ( $q1 == "b" && $q2 == "b" && $q3 == "b" && $q4 == "b" ) {
    header("Location: http://www.mostly-b.co.uk");
    exit;    
}

?>

Basically I need the script to echo 1 of 5 possible urls based on which answers are given

So for example, "url-mostly-a" would be echo'd if the user selected: aaaa aaab aaba abaa baaa aaac aaca acaa caaa

etc etc.....


Solution

  • 4 lines should do it:

    $count = array_count_values($_GET);
    arsort($count);
    $answers = array_keys($count);
    header("Location: http://www.mostly-{$answers[0]}.co.uk");
    
    1. count values occurences
    2. reverse sorting of values
    3. get an array with the keys (still sorted)
    4. use first value of array