Reputation: 215
I want to redirect to a random URL from a list.
Example : I have 3 URLs: Google.com, Facebook.com, yahoo.com.
<a href="<?php $sites[array_rand($sites)] ?>">Visit here</a>
So whenever users click the link they will be redirected to one of the 3 URLs in the array. I have tried this code but not working as needed:
$sites = array(
'http://www.google.com/',
'http://www.facebook.com/',
'http://www.yahoo.com/'
);
die();
Upvotes: 0
Views: 3608
Reputation: 524
The same functionality using javascript:
<a href='javascript:openUrl()'>Visit here</a>
<script>
var sites=['http://www.google.com/',
'http://www.msn.com/',
'http://www.yahoo.com/'
];
function openUrl(){
var i = Math.round(Math.random()*(sites.length-1));
window.location.href=sites[i];
return false;
}
</script>
Upvotes: 7
Reputation: 215
I got my code working.
<?php
$addresses = [
'http://www.google.com',
'http://www.facebook.com',
'http://www.youtube.com'
];
$size = count($addresses);
$randomIndex = rand(0, $size - 1);
$randomUrl = $addresses[$randomIndex];
?>
<a href="<?php echo $randomUrl; ?>">random url</a>
If you have a better code, Please make a suggestion.
Thank you
Upvotes: 1