tags:

views:

67

answers:

5

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?

+3  A: 

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.

cletus
+1  A: 

Slight change:

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

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.

RageZ
+1  A: 
$quiz = array_shift($module['QuizListing']);

if (null != $quiz) {
    echo "let's go";
}
Nicky De Maeyer
Note that `array_shift(...)` will modify the input array.
Inshallah
+1  A: 

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'];   
}
TheGrandWazoo