Jump to content

[SOLVED] Geting a value from an array


The Little Guy

Recommended Posts

Heres my code:
[code]$img = glob("radom_homepage_images/*.jpg");
echo'<img alt="image" src="'.array_rand($img).'">';[/code]

Here is the printed array:
[code]Array (
[0] => radom_homepage_images/IMG_0312.jpg
[1] => radom_homepage_images/IMG_0403.jpg
[2] => radom_homepage_images/IMG_0448.jpg
[3] => radom_homepage_images/IMG_0537.jpg
)[/code]

what is supposed to happen is it should get a random number from the array, and display the image. all that happens is it selects a random number, how do i get it to display the text that corresponds to the number?
Link to comment
https://forums.phpfreaks.com/topic/30852-solved-geting-a-value-from-an-array/
Share on other sites

Try setting a variable with the value of array_rand($img) and then echoing that variable.  There may be an issue with echoing array_rand($img) directly.

[code]
$img = glob("radom_homepage_images/*.jpg");
$the_img = array_rand($img);
echo'<img alt="image" src="'.$the_img.'">';
[/code]
Change
[code]<?php
$img = glob("radom_homepage_images/*.jpg");
echo'<img alt="image" src="'.array_rand($img).'">';
?>[/code]

to
[code]<?php
$img = glob("radom_homepage_images/*.jpg");
echo'<img alt="image" src="'.$img[array_rand($img)].'">';
?>[/code]

The array_rand() function returns a random index which you then have to use to get the entry.

Ken

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.