SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Zealot theslip's Avatar
    Join Date
    Jun 2008
    Location
    here
    Posts
    122
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Question random php block

    Hi,

    I'm trying to find a simple way to do the below:

    - I have a php page and have a small div that contains some content, <h2><p> etc

    - I want to have various different versions of that div content, store the different content in an external file or includes or something and call it in selecting the different content randomly on refresh.

    Any help would be great. I would like to stick to php rather than javascript if possible.

    Merci x

  2. #2
    SitePoint Wizard silver trophybronze trophy Cups's Avatar
    Join Date
    Oct 2006
    Location
    France, deep rural.
    Posts
    6,869
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    Here is the simplest way of doing it.

    random_divs.php
    PHP Code:
    <?php

    $divs 
    = array(
    '<h2>Div one</h2><p>content one</p>',
    '<h2>Div two</h2><p>content two</p>',
    '<h2>Div three</h2><p>content three</p>',
    );
    mypage.php
    PHP Code:
    // some html


    <?php
    include 'random_divs.php';

    echo 
    $divs[array_rand($divs)];
    ?>

    // more html

  3. #3
    SitePoint Zealot theslip's Avatar
    Join Date
    Jun 2008
    Location
    here
    Posts
    122
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Total legend, thanks so much cups! works a treat, Happy Xmas!

  4. #4
    SitePoint Wizard silver trophybronze trophy Cups's Avatar
    Join Date
    Oct 2006
    Location
    France, deep rural.
    Posts
    6,869
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    Thanks! Same to you.

    I suppose that if those divs became ginormous in size, then you could ech divs in their own file and include just the random one.

    *untested*

    random_div_3.php
    PHP Code:
    <h2>Random Three</h2>
    <
    p>Content three</p
    mypage.php
    PHP Code:
    // some html

    <?php
    $max 
    10;
    include 
    'random_divs_' rand(1$max) . '.php';
    ?>

    // more html
    You'd probably put the files in their own folder though. (eg: /random_divs/1.php)

    There are ways of simply adding files to a folder and your script picking one at random, so negating the need for maintaining a $max -- another day, eh?


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •