Goro
Goro

Reputation: 499

Rotate two banners 50/50

I have two banners which I display on the page but they didn't appear equal times on page refresh. I want they to rotate on every page refresh. Right now banner1 can show 10 times from 10 refresh and banner2 not even one time.

<?php
  $banner1 = '<a href="BANNER1_URL" target="_blank"><img src="BANNER1_IMG_SRC" alt="BANNER1_ALT" title="BANNER1_TITLE"></a>';
  $banner2 = '<a href="BANNER2_URL" target="_blank"><img src="BANNER2_IMG_SRC" alt="BANNER2_ALT" title="BANNER2_TITLE"></a>';
  $banners = array($banner1, $banner2);
  shuffle($banners);
?>
<div id="ban">
  <?php print $banners[0] ?>
</div>

I've tried to put for example rand(1,2) but the page crash. This is what I've tried

    <?php
  $banner1 = '<a href="BANNER1_URL" target="_blank"><img src="BANNER1_IMG_SRC" alt="BANNER1_ALT" title="BANNER1_TITLE"></a>';
  $banner2 = '<a href="BANNER2_URL" target="_blank"><img src="BANNER2_IMG_SRC" alt="BANNER2_ALT" title="BANNER2_TITLE"></a>';
  $banners = array($banner1, $banner2);
  $num = rand (1,2);
  shuffle($banners);
?>
<div id="ban">
  <?php print $num($banners[0]) ?>
</div>

Upvotes: 0

Views: 308

Answers (1)

Sander
Sander

Reputation: 1314

With the number that you randomly get you need to get that index from the list of banners;

<?php
  $banner1 = '<a href="BANNER1_URL" target="_blank"><img src="BANNER1_IMG_SRC" alt="BANNER1_ALT" title="BANNER1_TITLE"></a>';
  $banner2 = '<a href="BANNER2_URL" target="_blank"><img src="BANNER2_IMG_SRC" alt="BANNER2_ALT" title="BANNER2_TITLE"></a>';
  $banners = array($banner1, $banner2);
  $num = rand (0,1);
?>
<div id="ban">
  <?php print $banners[$num] ?>
</div>

Also change your "random-generator" to get 0 or 1 as the index and remove the shuffle (as mentioned by MatsLindh in the comments)

EDIT: As requested in the comments, here is an example of how to store which banner was shown in the SESSION and then show the other.

<?php
  $banner1 = ...
  $banner2 = ...
  $banners = array($banner1, $banner2);
  $bannerIndex = 0;
  if(isset($_SESSION['bannerIndex'])){
     $bannerIndex = (intval($_SESSION['bannerIndex']) + 1) % 2;
  }
  $_SESSION['bannerIndex'] = $bannerIndex;
?>
<div id="ban">
  <?php print $banners[$bannerIndex]; ?>
</div>

This is just to give you an idea and has not been tested.

Upvotes: 1

Related Questions