mt_rand doesn't work

Discussion about any web related scripting languages like JavaScript, ASP, and PHP.
Post Reply
maichel
Rank 0 - Newcomer
Rank 0 - Newcomer
Posts: 6
Joined: Mon Oct 05, 2015 8:13 am

mt_rand doesn't work

Post by maichel » Mon Oct 05, 2015 8:18 am

Hello,
I have written a function in php. If you refresh the page you see a another image, but this doesn't work.

Now I see the 4 images in the browser, next to each other. But I want to see 1 image and if I refresh the page you see a random other image.

Can someone help me what is wrong, why didn't work mt_rand?
thanks in advance.
my code is:

Code: Select all

function photorandom() 
{
    $photo = array("www.google.nl" => "1.jpg", "www.bing.com" => "2.jpg", "3.jpg", "4.jpg");
    
    $random = mt_rand(0, (count($photo)-1)); 
    $randomImage = $photo[$random];
    
    foreach($photo as $link => $randomImage) {
    echo "<a href='http://{$link}'><img src=' {$randomImage} ' width='500'></a>"; 
    }
    
   
 
}

photorandom();

User avatar
Lou
Rank V - Professional
Rank V - Professional
Posts: 258
Joined: Fri Jul 29, 2005 5:55 pm
Location: CO
Contact:

Re: mt_rand doesn't work

Post by Lou » Mon Oct 05, 2015 6:47 pm

Why don't you just use the php shuffle(array) function?

Code: Select all

function photorandom()
{
    $photo = array("www.google.nl" => "1.jpg", "www.bing.com" => "2.jpg", "3.jpg", "4.jpg");
   // seed ran gen
   srand(time());
  // randomize the order in the array
  shuffle($photo);
  return $photo[0];
 }
Lou
Say what you will about Sisyphus. He always has work.

User avatar
Albert Wiersch
Site Admin
Site Admin
Posts: 3347
Joined: Sat Dec 11, 2004 9:23 am
Location: Near Dallas, TX
Contact:

Re: mt_rand doesn't work

Post by Albert Wiersch » Mon Oct 05, 2015 7:46 pm

I threw in some variable dumps (exports). You can better see what's going on. If you look at the array, there is only $photo[0] and $photo[1] because the other values have keys instead of array indexes, so $photo[2] and $photo[3] are NULL.

Code: Select all

<?php
function photorandom() 
{
    $photo = array("www.google.nl" => "1.jpg", "www.bing.com" => "2.jpg", "3.jpg", "4.jpg");
   
    echo '<p>$photo: '.var_export($photo,true);
    
    $random = mt_rand(0, (count($photo)-1)); 

    echo '<p>$random: '.var_export($random,true);

    $randomImage = $photo[$random];

    echo '<p>$randomImage: '.var_export($randomImage,true);
        
    echo '<p>';
    
    foreach($photo as $link => $randomImage) {
//    echo "<a href='http://{$link}'><img src=' {$randomImage} ' width='500'></a>"; 
     echo "{$link} / {$randomImage} <br>"; 
    }
}

photorandom();
?>
The output of the above is something like:

Code: Select all

$photo: array ( 'www.google.nl' => '1.jpg', 'www.bing.com' => '2.jpg', 0 => '3.jpg', 1 => '4.jpg', )

$random: 3

$randomImage: NULL

www.google.nl / 1.jpg 
www.bing.com / 2.jpg 
0 / 3.jpg 
1 / 4.jpg 
Image
Albert Wiersch

Post Reply