0

Here's my code:

$quizId = '';
foreach ($module['QuizListing'] as $quizListing)    {
    if ($quizListing['id']) {
        $quizId = $quizListing['id'];
        break;
    }
}

Is there a better way of doing this?

2
  • 1
    @baker: $module['QuizListing'] is coming from some SQL query ? Commented Nov 18, 2009 at 9:06
  • 1
    Better use isset to avoid warnings. Commented Nov 18, 2009 at 9:10

5 Answers 5

3

What you're doing is reasonable assuming that:

  • multiple quiz listings appear; and
  • not all of them have an ID.

I assume from your question that one of both of these is not true. If you want the first quiz listing then do this:

$listing = reset($module['quizListing']);
$quizId = $listing['id'];

The reset() function returns the first element in the array (or false if there isn't one).

This assumes every quiz listing has an ID. If that's not the case then you can't get much better than what you're doing.

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

Comments

1

Slight change:

$quizId = '';
foreach ($module['QuizListing'] as $quizListing)    {
    if (isset($quizListing['id'])) {
        $quizId = $quizListing['id'];
        break;
    }
}

Comments

1

to answer if this array is coming from a database you probably have to better to filter your query not to include those row at first place

something like

SELECT * from Quiz WHERE id <> 0

this would give you an array usable without any other processing.

Comments

1
$quiz = array_shift($module['QuizListing']);

if (null != $quiz) {
    echo "let's go";
}

1 Comment

Note that array_shift(...) will modify the input array.
1

Using array_key_exists you can check if the key exists for your array. If it exists, then assign it to whatever you want.

if (array_key_exists('id', $quizListing)) {
  $quizId = $quizListing['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.