1 Reply Latest reply on Nov 3, 2010 2:05 AM by osgood_

    Newbie question about PHP and "array_rand"

    jyeager11 Level 1

      I don't know too much about PHP, other than slightly modifying code given to me to suit my purposes.

       

      Here's some php randomizing code someone sent to me that I've been using :

      <?php $a[] = 'test1.php'; $a[] = 'test2.php'; $a[] = 'test3.php/'; ?>

       

      <a href="<?php echo $a[array_rand($a)]; ?>">RANDOM LINK</a>

       

      Simple enough. On every reload of the page, the link will randomly point to one of the three arrays, which happens to be web pages.

       

      Now, I wanted the page to randomly display divs much in the same way. But I'd have to put the entire DIV contents (including IMGs and live text) in the arrays. I don't know how to do that. The ' and < > characters alone will break the thing.

       

      What's the simplest way for me to achieve what I want to achieve here?

        • 1. Re: Newbie question about PHP and "array_rand"
          osgood_ Level 8

          mjyeager wrote:

           

          I don't know too much about PHP, other than slightly modifying code given to me to suit my purposes.

           

          Here's some php randomizing code someone sent to me that I've been using :

          <?php $a[] = 'test1.php'; $a[] = 'test2.php'; $a[] = 'test3.php/'; ?>

           

          <a href="<?php echo $a[array_rand($a)]; ?>">RANDOM LINK</a>

           

          Simple enough. On every reload of the page, the link will randomly point to one of the three arrays, which happens to be web pages.

           

          Now, I wanted the page to randomly display divs much in the same way. But I'd have to put the entire DIV contents (including IMGs and live text) in the arrays. I don't know how to do that. The ' and < > characters alone will break the thing.

           

          What's the simplest way for me to achieve what I want to achieve here?

           

          You use 'include' files. The array below will now 'randomly' include one of three files in your site folder.

           

          ?php $a[] = 'one.php'; $a[] = 'two.php'; $a[] = 'three.php'; ?>

           

          <?php include $a[array_rand($a)]; ?>

           

           

          Typically in your 'one.php' file you will have something like:

          <div>
          <p>This is div 1</p>
          <img src="images/one.jpg" width="200" height="200" >
          </div>

           

           

          Please do not include any other code in the 'include' files other than the code needed, i.e, no html, body, meta tags etc. Just the basic code that makes up the <div> content.