Otis Wright
Otis Wright

Reputation: 2110

Using the last item in a PHP array

Hello I am using Cockpit CMS as the backend for a new project, and I have set my index.php to have a background image.

Now I want the user to be able to change the images in a "gallery" without deleting the other images and I want to load up the last image in the "gallery".

Here is the Cockpit Galleries documentation.

I can do this with this:

<?php foreach(gallery('Backgrounds') as $images): ?>

    <?php thumbnail($images["path"]) ?>

<?php endforeach;?>

however this loads all the images and is really slow and inefficient, what I want to do is load up the images into an array and use the last image, this is what I have so far:

<?php $images = cockpit("galleries")->gallery('Backgrounds'); ?>

<?php thumbnail(end($images["path"])) ?>

Update:

Checked PHP log am receiving this error:

PHP Warning:  end() expects parameter 1 to be array, null given in /Users/username/Developer/Beardedweb/index.php on line 10

Sorry not very PHP proficient.

Cheers, Otis Wright.

Upvotes: 0

Views: 117

Answers (1)

John Conde
John Conde

Reputation: 219884

You're close. First you have to get the last element of the array and then get it's value.

<?php 
$img = end($images);
thumbnail($img["path"]);
?>

Upvotes: 1

Related Questions