/    Sign up×
Community /Pin to ProfileBookmark

Random Picture Script

I’m trying to get a random picture script that I wrote working right, but i’m having some issues with it repeating. Basically this script generates 16 random numbers between 1 and 149. I then check to make sure the number isn’t already in the array (this is the part thats not working), and if its not, i add it to the array. basically, my pictures are named 001.jpg – 149.jpg

[code=php]$numpics=149;
$array=array();
$pics=array_pad($array,16,0);
for($i=1;$i<20;$i++)
{
$temp=str_pad(rand(1,$numpics),3,”0″,PAD_LEFT);
while(array_search($temp,$pics)<0){$temp=str_pad(rand(1,$numpics),3,”0″,PAD_LEFT);}
$pics[$i]=$temp;
}[/code]

to post a comment
PHP

2 Comments(s)

Copy linkTweet thisAlerts:
@JonaAug 07.2004 — [font=trebuchet ms]So your only problem is that the same random number occurs more than once? Create another array to hold the array keys that have already been used.[/font]
Copy linkTweet thisAlerts:
@JonaAug 07.2004 — [font=trebuchet ms]Does this work for you?[/font]

[code=php]
<?php

$numpics=149;
$pics=array_pad(array(),16,0);
$picHold = $pics;

for($i=1;$i<20;$i++)
{
$temp=str_pad(rand(1,$numpics),3,"0",PAD_LEFT);
while(array_search($temp,$pics)<0)
{
$temp=str_pad(rand(1,$numpics),3,"0",PAD_LEFT);
}

if(!isset($picHold[$temp])){
$picHold[$temp] = $i;
$pics[$i]=$temp;
echo $pics[$i].".jpg<br>";
} else {
$i--;
}
}

?>
[/code]
×

Success!

Help @Sam spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.18,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...