Reputation: 3
I would like to convert this javascript (which works correctly) into a PHP function, so that all this code does not have to appear in the source code of the webpage.
<script type="text/javascript">
var images = [],
index = 0;
images[0] = "<a href = 'http://www.random_target1.com' target='_blank'><img src='//www.random_target1.com/random_banner.jpg' width='120' /></a>";
images[1] = "<a href = 'http://www.random_target2.com' target='_blank'><img src='//www.random_target2.com/random_banner.jpg' width='120' /></a>";
images[2] = "<a href = 'http://www.random_target3.com' target='_blank'><img src='//www.random_target3.com/random_banner.jpg' width='120' /></a>";
index = Math.floor(Math.random() * images.length);
document.write(images[index]);
</script>
I tried this PHP function in the PHP file, and thought I could call its result, from the HTML file, so only determined value would appear in HTML source code. This code broke the page, though.
public function getRandom()
{
$images = array();
$index = 0;
$images[0] = "<a href = 'http://www.random_target1.com' target='_blank'><img src='//www.random_target1.com/random_banner.jpg' width='120' /></a>";
$images[1] = "<a href = 'http://www.random_target2.com' target='_blank'><img src='//www.random_target2.com/random_banner.jpg' width='120' /></a>";
$images[2] = "<a href = 'http://www.random_target3.com' target='_blank'><img src='//www.random_target3.com/random_banner.jpg' width='120' /></a>";
$index = Math.floor(Math.random() * $images.length);
return $images[$index];
}
Upvotes: 0
Views: 1670
Reputation: 6346
Note I use mt_rand instead of rand. It's generally considered a better random number function.
<?php
$images = array();
$images[0] = "<a href = 'http://www.random_target1.com' target='_blank'><img src='//www.random_target1.com/random_banner.jpg' width='120' /></a>";
$images[1] = "<a href = 'http://www.random_target2.com' target='_blank'><img src='//www.random_target2.com/random_banner.jpg' width='120' /></a>";
$images[2] = "<a href = 'http://www.random_target3.com' target='_blank'><img src='//www.random_target3.com/random_banner.jpg' width='120' /></a>";
$randIndex = mt_rand(0,sizeof($images)-1);
echo $images[$randIndex];
?>
Upvotes: 1
Reputation: 21449
$images = array(
"<a href = 'http://www.random_target1.com' target='_blank'><img src='//www.random_target1.com/random_banner.jpg' width='120' /></a>",
"<a href = 'http://www.random_target1.com' target='_blank'><img src='//www.random_target1.com/random_banner.jpg' width='120' /></a>",
"<a href = 'http://www.random_target1.com' target='_blank'><img src='//www.random_target1.com/random_banner.jpg' width='120' /></a>"
);
$index = rand(0, count($images)-1);
echo $images[$index];
Upvotes: 1