phpforeacharrayiterator

PHP foreach skip iterate in an array


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.


Solution

  • 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'] : '';