0

This array is being created correctly, although i need to pick one then print it which isnt happening for me...any ideas?

<?php
$bgimagearray = array();
$iterator = new DirectoryIterator("/home/sites/yellostudio.co.uk/public_html/public/themes/yello/images/backgrounds");
foreach ($iterator as $fileinfo) {
    if ($fileinfo->isFile() && !preg_match('/-c\.jpg$/', $fileinfo->getFilename())) {
        $bgimagearray[] = "'" . $fileinfo->getFilename() . "'";
    }
}

$bgimage = array_rand  ( $bgimagearray, 2 );


?>
<img src="<?php echo URL_PUBLIC; ?>public/themes/yello/images/backgrounds/<?php echo $bgimage; ?>" alt=""/>

1 Answer 1

2

Qutoing the PHP manual:

If you are picking only one entry, array_rand() returns the key for a random entry. Otherwise, it returns an array of keys for the random entries. This is done so that you can pick random keys as well as values out of the array.

You're passing 2 as second argument and therefore are getting an array of keys which you#re using as string in <?php echo $bgimage; ?>.

To solve this you have to write something like:

<?php
// ...
$bgimage = array_rand  ( $bgimagearray);
?>
<img src="<?php echo URL_PUBLIC; ?>.../<?php echo $bgimagearray[$bgimage]; ?>" alt=""/>
Sign up to request clarification or add additional context in comments.

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.