开发者

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

开发者 https://www.devze.com 2022-12-12 07:11 出处:网络
Here\'s my code: $quizId = \'\'; foreach ($module[\'QuizListing\'] as $quizListing){ if ($quizListing[\'id\']) {

Here's my code:

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

Is there a开发者_如何学Python better way of doing this?


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.


Slight change:

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


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.


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

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


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

精彩评论

暂无评论...
验证码 换一张
取 消