www.webdeveloper.com
Results 1 to 4 of 4

Thread: How to concatenate number at end of variable name

Hybrid View

  1. #1
    Join Date
    Oct 2012
    Posts
    2

    How to concatenate number at end of variable name

    hey,

    i want to concatenate and echo the variable having number at the end of it. like varA1 , varA2 , varA3 .. .... the number generated by rand() function;
    I am using
    <?php
    $varA1 = "Loin";
    $varA2 = "Duck";
    $varA3 = "Apple;
    $varA4 = "Tomato";

    $num = rand(1, 4);

    ?>
    Now i want to print variable value randomly as everytime webpage refresh

  2. #2
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,222
    I suggest you use an array instead of individual scalar variables, making things much simpler:
    PHP Code:
    $var = array();
    $var[1] = 'foo';
    $var[2] = 'bar';
    $var[3] = 'fubar';
    $num rand(1,3);
    echo 
    $var[$num]; 
    "Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
    ~ Terry Pratchett in Nation

    eBookworm.us

  3. #3
    Join Date
    Oct 2012
    Posts
    2
    thanks a lot.. problem solved by your technique

  4. #4
    Join Date
    Oct 2010
    Location
    Ohio
    Posts
    233
    However if you did need to use scalar variables for some reason, instead of arrays, you could do so using braces:

    PHP Code:
    $var1 "something";
    $var2 "something else";
    echo ${
    'var'.rand(1,2)}; 
    ~Ryan
    www.rdennispallas.com <-- Personal Site, changing regularly cuz its ugly.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

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



Recent Articles