0

I have an array, and i want to find all values where correct => true:

   $quiz_array = array (
            'question1' => array (
                        'q1a1' => array (
                                  'correct' => FALSE,
                                  'answer' => 'false answer1'
                        ),
                        'q1a2' => array (
                                  'correct' => FALSE,
                                  'answer' => 'false answer2'
                        ),
                        'q1a3' => array (
                                  'correct' => FALSE,
                                  'answer' => 'false answer3'
                        ),                  
                        'q1a4' => array (
                                  'correct' => TRUE,
                                  'answer' => 'correct answer'
                        )
            )
    );

I want to do a search, where it would return q1a4 in this case, because correct => TRUE. I trid using in_array and array_search but no luck. Any suggestions?

1

4 Answers 4

0

Here is your answer,

foreach($quiz_array as $key=> $value) {
  foreach($quiz_array[$key] as $key=> $value) {
    if( $value["correct"] ) {
        echo $key ."<br>";  
    }
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0
foreach ($quiz_array as $key => $value) {
 if (strpos($value, '<name of value you want to search>') !== false) {
    $new_key = $key;
    break;
  }
}

Comments

0
function correct($array) {
    return $array('correct');
}

$results= array();
foreach($quiz_array as $key => $value) {
    $correct= array_filter($value, 'correct');
    $results[$key]= $correct;
}

print_r($results);

Comments

0

You could do something like this:

$correctAnswers = array();
foreach ($quiz_array as $question => $answers) {
  $correctAnswers[$question] = array_filter($answers, function($v) { 
    return $v['correct']; 
  });
}
var_dump($correctAnswers); // array('question1' => array('q1a4' => array('correct' => true, 'answer' => 'correct answer')));

If you want to return just the correct answers key (eg. q1a41) you could do:

$correctAnswers = array();
foreach ($quiz_array as $question => $answers) {
  foreach ($answers as $k => $a) {
    if ($a['correct']) { 
      $correctAnswers[$question] = $k;
    }
  }
}
var_dump($correctAnswers); // array('question1' => 'q1a4');

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.