how can we randomly change image when we refresh the page every time in php
+2
A:
- Create an array of image names.
- Generate a random number between 0 and the length of the array.
- Generate an
<img>
tag using the image name corresponding to that random number.
ChristianLinnell
2009-07-16 06:28:00
Beat me ): ` `
Ian Elliott
2009-07-16 06:29:29
That's 'cause he didn't stop to write code ;-)
beggs
2009-07-16 06:30:25
Ah but you have code :-)
ChristianLinnell
2009-07-16 06:30:54
+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
2009-07-16 06:29:00
Just make `alt` an empty value... if the `alt` text cannot entirely replace the image in its context, it should be empty.
Blixt
2009-07-16 06:39:38
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
2009-07-16 06:43:42
I agree with Blixt. Unless your filenames are sensible enough that you could drop them in the alt text instead.
ChristianLinnell
2009-07-16 07:19:25
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
2009-07-16 13:36:24