Page 1 of 1

PHP Shuffle Array

Posted: Tue Feb 23, 2010 1:05 pm
by ksimpkins
I am new to PHP and I was trying to create an array and have it shuffle some write content.

The website address is http://www.travelvi.com/template/us-vir ... dings.html -- I am trying shuffle ads randomly

please help me with this..

<?php
$ads = array (WriteContent('ad-stt-weddings-elisha-orin-photography'), WriteContent('ad-stt-weddings-brandi-mays-videographer'));
shuffle($ads);
?>

Re: PHP Shuffle Array

Posted: Tue Feb 23, 2010 2:21 pm
by requinix
Congratulations! You won a prize for not telling us what you need help with!

You can find your prize here.

Re: PHP Shuffle Array

Posted: Tue Feb 23, 2010 2:36 pm
by McInfo
I'm just guessing that this is the problem: PHP can't change page content after it has been sent to the browser. In other words, you can't shuffle the ads if they have already been written.

This might work; however, it is unclear how the "ad-..." strings influence your application and what the WriteContent() function does.

Code: Select all

<?php
$ads = array ('ad-one', 'ad-two');
shuffle($ads);
foreach ($ads as $ad) {
    WriteContent($ad);
}
Edit: This post was recovered from search engine cache.

Re: PHP Shuffle Array

Posted: Mon Mar 08, 2010 9:29 am
by ksimpkins
Sorry everyone.. This is what I am trying to do.. but I would like to only write a certain number from the array.. for example.. if I had 20 items in the array, but I would want it to randomly pick 5 of the them and display them.

Any thoughts?

<?php
$ads = array (
'ad-stt-weddings-elisha-orin-photography',
'ad-stt-weddings-brandi-mays-videographer',
'ad-stt-weddings-sugar-and-spice-artistry',
'ad-stt-weddings-weddings-the-island-way');
shuffle($ads);
foreach ( $ads as $ad ) {
WriteContent($ad);
}

Re: PHP Shuffle Array

Posted: Mon Mar 08, 2010 10:02 am
by AbraCadaver
This?

Code: Select all

shuffle($ads);
for($i=1; $i<=5; $i++) {
   WriteContent($ads[$i]);
}
Or...

Code: Select all

$rand_ads = array_rand($ads, 5);
foreach($rand_ads as $ad) {
       WriteContent($ads[$ad]);
}
Or...

Code: Select all

$rand_ads = array_rand(array_flip($ads), 5);
foreach($rand_ads as $ad) {
       WriteContent($ad);
}