• home
  • forum
  • my
  • kt
  • download
  • Variables in Variables

    Author: 2007-08-11 18:37:05 From:

    It allows part of a variables name to be a variable.

    So, what does that exactly mean?
    Code: Select all
    $y = 1;
    $x1 = "test";
    echo $x$y;

    In that example, the script would parse the variables name to be $x1. From there PHP would move forward to echoing $x1. So the script would print out the value test which we assigned to X1.

    You will learn about arrays shortly, but here is a cool script you can play with.
    I will be using the random function, which is quite simple.

    Code: Select all
    random(1,5);

    How does this work?
    It picks a random between the first number in the second number.

    In any PHP function, you can use a variable as input so we could try something like this:
    Code: Select all
    $max = 5;
    $min = 1;
    random($min, $max);


    At this stage our script we are not doing anything with the output of random so we will get an error.

    Here is a fix:
    Code: Select all
    $max = 5;
    $min = 1;
    $random = random($min, $max);


    Now, lets fix this up and make a random quotation script!
    Code: Select all
    $quote1 = "Hey, this is the first quote";
    $quote2 = "Hey, the second quote could be first?";
    $quote3 = "The second quote could be first, but I could be third and better than the second post";
    $quote4 = "Quote 4 is cool!";
    $quotecount = 4;
    $randomquotenum = random(1, $quotecount);
    $randomquote = $quote$randomquotenum;
    echo $randomquote;

    You can of course change any of the quotes, add new ones and remove quotes. Make sure to update $quotecount.

    I want you to also know, that this is definately not the best (or easiest) way to print random quotes. You will always use the random function, but you must also learn arrays.

    discuss this topic to forum

    relation tutorial

    No relevant information

    Category

      Ad Management (4)
      Calendars (3)
      Chat Systems (7)
      Content Management (6)
      Cookies and Sessions (8)
      Counters (8)
      Database Related (8)
      Date and Time (9)
      Development (6)
      Discussion Boards (7)
      E Commerce (6)
      Email Systems (9)
      Error Handling (5)
      File Manipulation (10)
      Flash and PHP (4)
      Form Processing (7)
      Guestbooks (8)
      Image Manipulation (3)
      Installing PHP (5)
      Introduction to PHP (9)
      Link Indexing (6)
      Mailing List Management (8)
      Miscellaneous (10)
      Networking (6)
      News Publishing (6)
      OOP (8)
      PEAR (6)
      PHP vs Other Languages (2)
      Polls and Voting (5)
      Postcards (0)
      Randomizing (8)
      Redirection (8)
      Searching (6)
      Security (6)
      Site Navigation (7)
      User Authentication (10)
      WAP and WML (7)
      Web Fetching (0)
      Web Traffic Analysis (11)
      XML and PHP (0)

    New

    Hot