PHPでランダムな数値を取得する場合、rand
関数とmt_rand
関数があります。
rand(最小値, 最大値)
mt_rand(最小値, 最大値)
機能はどちらも同じようですがmt_rand
のほうがだいぶ高速らしいです。以前はrand
を使用していましたが現在はmt_rand
のほうが推奨されていますのでこちらを使うようにしましょう。
バナータグをそのまま貼る方法
PHPでバナーを複数ランダム表示させたい場合、そのままタグをコピペで使う方法になります。アフィリエイトバナーなどにも使えるかもしれませんね。
<?php $image_rand = array( '<a href="http://example.com" target="_blank"><img src="http://example.com/imgA.jpg" /></a>', '<a href="http://example.com" target="_blank"><img src="http://example.com/imgB.jpg" /></a>', ); $image_rand = $image_rand[mt_rand(0, count($image)-1)]; echo $image_rand; ?>
サイト内で画像のみをランダム表示する方法
こちらは画像のみを切り替えてランダム表示させます。画像名のみだけなのでaltなどは同じものを使えます。
<?php $image_rand = array( "img/img1.jpg", "img/img2.jpg", "img/img3.jpg", ); $image_rand = $image_rand[mt_rand(0, count($image_rand)-1)]; echo '<img src="'.$image_rand.'" alt="">'; ?>
テキストをランダム表示する方法
こちらは同じくテキストを切り替えてランダム表示させます。
<?php $text_rand = array( "テキストA", "テキストB", "テキストC", ); $text_rand = $text_rand[mt_rand(0, count($text_rand)-1)]; echo $text_rand; ?>