Keeping track of 2 key array

Question

I'm trying to implement a polling system where if the user lands on a particular poll page and actually answers the question, then the id and their option will be logged. For example, let's say the id of that question is 67 and they answered option 2, then I want the array to look something like this: 67:2. The log array data will be kept in a SESSION variable, and each time the user answers a question it'll add on to this array. When the user tries to navigate to a poll he/she answered already, then it'll display the answered option.

I know I could use concatenate and the in_array function if this was an array of only numbers, like "3,2,1,5,6" but how can I do this for this type of array? ("3:1, 2:2, 1:1") where the first digit is the id and the second digit is the option chosen. How do I use if (in_array($id)) when after concatenation it'll be something like this "3:1"?


Show source
| php   | arrays   | session-variables   2017-01-01 00:01 1 Answers

Answers to Keeping track of 2 key array ( 1 )

  1. 2017-01-01 00:01

    I would say, you can do this way:

    // Log an answer:
    $_SESSION["polls"][$question] = $answer;
    

    This way, it will be logging:

    {
      "polls": {
        "question-6": "answer-2",
        "question-4": "answer-1"
      }
    }
    

    So there will be no duplication. To check if the user has answered already, you can do this:

    in_array("question-6", array_keys($_SESSION["polls"]))
    

    This will give you if the user has answered question 6 or not.

    PHP Script

    <?php
        header("Content-type: text/plain"); session_start();
        // Log few questions and answers.
        $question = "question-67";
        $answer = "answer-2";
        $_SESSION["polls"][$question] = $answer;
        $question = "question-55";
        $answer = "answer-1";
        $_SESSION["polls"][$question] = $answer;
        $question = "question-42";
        $answer = "answer-3";
        $_SESSION["polls"][$question] = $answer;
        // Let's check if the next question, which will be the same one, has been answered or not.
        $question = "question-67";
        $answer = "answer-2";
        if (in_array($question, array_keys($_SESSION["polls"])))
            echo "Question has been answered.";
        else
            echo "Question not answered.";
    ?>
    

    I get the output as:

    Question has been answered.
    

Leave a reply to - Keeping track of 2 key array

◀ Go back