tags:

views:

57

answers:

2
+1  Q: 

change image

how can we randomly change image when we refresh the page every time in php

+2  A: 
  1. Create an array of image names.
  2. Generate a random number between 0 and the length of the array.
  3. Generate an <img> tag using the image name corresponding to that random number.
ChristianLinnell
Beat me ): ` `
Ian Elliott
That's 'cause he didn't stop to write code ;-)
beggs
Ah but you have code :-)
ChristianLinnell
+8  A: 

Load the possible image extensions into an array. Use rand() to generate a random integer within range of the length of this array, and display it in your HTML.

$images = array('img1.png', 'img2.png');
$rand = array_rand($input, 1); // number of random keys to generate
echo "<img src=\"".$images[$rand[0]]."\" alt=\"this image\">";
Ian Elliott
*wonders about the alt text...*
ChristianLinnell
*As long as it validates :)*
Ian Elliott
Just make `alt` an empty value... if the `alt` text cannot entirely replace the image in its context, it should be empty.
Blixt
Oh and also have a look at the http://www.php.net/array_rand function... `$images[array_rand($images)];` It's especially useful when you want several random entries. `$keys = array_rand($images, 3);`
Blixt
I agree with Blixt. Unless your filenames are sensible enough that you could drop them in the alt text instead.
ChristianLinnell
I agree with you that array_rand would be a good improvement. As for the alt text I think you're over analyzing it, of course it can be changed to anything.
Ian Elliott