0

I have an array of albums $albums[] and an array of photos $photos. I want to echo out each album with all matching photos and am using this code:

<?php
    ...

    foreach($albums as $album){
        if( $album[photo_count] !== 0 ){
            if($album[photo_count] > 10){
                $limit = 10;
            }

            $boxID = $id = substr( $album[aid], strrpos( $album[aid], '_' )+1 );     
?>
            <div id="gal-<?=$boxID?>-box" class="box gallery-album">
            <?
            $i = 0;

            foreach($photos as $photo){                             
                if( ($photo[aid] == $album[aid]) && ($i < $limit) ){
                    echo '<img src="'.$photo[src_big].'" alt="'.$photo[caption].'"/>';
                    $i++;
                }
        } 

    ?>
    </div>
    </div>

    <?
    }   
}

This works fine, but feels very inefficient. Is there a better way of coding this?

1
  • You can set the $limit outside of the first loop, it's constant anyway. If you want to improve the code smell, JRL has the answer below. Commented Oct 8, 2011 at 13:17

2 Answers 2

2

I wouldn't worry about whether or not it seems efficient, but rather whether it is clean and maintainable.

As such, I would suggest you separate the code into two functions, one which finds all photos associated with an album, and one which creates the html for displaying it, e.g. something like:

/**
 * Gets the photos for a given album
 * @param int $albumId the album identifier
 * @return array an array of photos associated with this album,
 *               or an empty array if there are none
 */
function getPhotos($albumId);

/**
 * Outputs an html div for each photo in the photo array
 * @param array $photos an array of photos
 */
function displayPhotos($photos);

You can also use some of the SPL iterators to make the code cleaner, such as LimitIterator, which you would use to limit the array passed to displayPhotos for a given album.

Sign up to request clarification or add additional context in comments.

Comments

0

Well, it's a problem of how your arrays are structured. I don't think you could achieve this in a better way. It'd be nice to have the photos element inside each album element in your $albums array, but you'd have to pre-parse it, which would be useless.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.