baker
baker

Reputation: 241

PHP: A better way of getting the first value in an array if it's present

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?

Upvotes: 0

Views: 122

Answers (5)

TheGrandWazoo
TheGrandWazoo

Reputation: 2897

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

Upvotes: 1

NDM
NDM

Reputation: 6830

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

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

Upvotes: 1

RageZ
RageZ

Reputation: 27313

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.

Upvotes: 1

Fenton
Fenton

Reputation: 250892

Slight change:

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

Upvotes: 1

cletus
cletus

Reputation: 625047

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.

Upvotes: 3

Related Questions