PHP foreach skip iterate in an array

被刻印的时光 ゝ 提交于 2019-12-02 19:37:32

问题


I want to skip iterate in a php foreach anytime when I receaive "Undifined index". Here is my code so far:

<?php
$albums = $facebook->api("/me/albums");
$i=0;
foreach ($albums['data'] as $album) {
    if (is_null($album['cover_photo'])) continue;
    if($i==8) break;
    $album_id = $album['id'];
    $album_cover = $album['cover_photo'];
    $album_name = $album['name'];
    $album_count = $album['count'];
    $covers = $facebook->api("/" . $album_cover . "");
    $source = $covers['source'];
    ?>

If I don't have the if is_null syntax the code breaks but I receive the error that cover_photo index is undefined (it is the normal behaviour). At least if I could not display the error it could be enough.


回答1:


Instead try,

if (!isset($album['cover_photo'])) continue;

Or better check the variable isset before assigning it.

$album_cover = (isset($album['cover_photo'])) ? $album['cover_photo'] : '';


来源:https://stackoverflow.com/questions/15884909/php-foreach-skip-iterate-in-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!