0

I am looping through a series of inputs and saving their values to an array. Each element in the array is a special class that has a name (so it can be uniquely identified) and an answer (initialized as null, populated in the following loop):

class Question
{
    public name;
    public answer;
}

...

foreach ($quiz_questions as $q)
{
    $inputName = $q->name;
    $response = $_POST[$inputName];
    $q->answer = $response;
    print_r($q->answer);
}
print_r($quiz_questions);

When I print each individual answer during the iteration, the values come out correctly, but when I print the entire array after the loop, the answer components are NULL like they were before the loop.

Any idea what the problem is?

3
  • do u define $quiz_questions? Commented Oct 28, 2015 at 7:07
  • 3
    foreach ($quiz_questions as &$q) Commented Oct 28, 2015 at 7:08
  • no,where u define $quiz_questions?same as a $quiz_questions=array(1,2,3) Commented Oct 28, 2015 at 7:10

1 Answer 1

1

As you say that each element in the array is a class, use the get_object_vars() function to access the class attributes.

get_object_vars($quiz_questions)); 

should do the work.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.