0

I have an array:

$quizzes = array();
            $Quiz = array(
                'quiz_id'   => $quiz_id,
                'correct'   => $correctAnswers
            );
            $quizzes[] = $Quiz;

$quizzes is an array which contains many quizzes called Quiz, which in turn have $Quiz['quiz_id'] and $Quiz['correct']. Now what I'm trying to do is to select a particular quiz from the list of quizzes in $quizzes where quiz_id=1.

If such quiz exists, I would like to echo quiz is found. If no $Quiz with such id exists, echo no quiz is found.

A simple solution that I came up with is to do a foreach loop.

foreach($quizzes as $Quiz) if($Quiz['quiz_id'] == 1) {} else {}

However, since I have more than 1 quiz, it returns the else statement as many times as there are $Quiz['quiz_id'] != 1 which is many many times.

0

2 Answers 2

3

Indexing your array such as $quizzes[ $quiz_id ] = $Quiz; would permit you to go straight to that item in the array.

So take your existing line of

$quizzes[] = $Quiz;

and change it to

$quizzes[ $quiz_id ] = $Quiz;

then you can use

if( isset( $quizzes[ $quiz_id ] ) )
{
  echo 'found the quiz!';
}
else
{
  echo 'no quiz found';
}

where $quiz_id is the id of the quiz you wish to locate

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

3 Comments

But the thing is that $quizzes[1] corresponds to some $Quiz, which does not necessarily have quiz_id of 1?
Or let's say $quizzes[0] is the first ever $Quiz entered. If a user completed 5th test first, I would add $Quiz into this array where quiz_id=5. Then if $quizzes[5] doesn't yet exists, but there is a quiz with quiz_id 5
I think I see what you mean, you are indexing the positions of these quizzes based on id, so an array can be empty for the first 100 point $quizzess[0 to 99] but have $quizzes[100] as the first one if the user completes 100th quiz
1
$id = 1;
array_filter($quizzes, function($v) use($id) {return $v['quid_id'] == $id;});

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.