Concate variable name.

Discussion in 'PHP' started by Jeremy1026, Aug 17, 2010.

  1. #1
    I am trying to dynamically change the name of a variable to check against it. Is this possible in PHP.

    I have previously designated variables $wk1, $wk2, $wk3, $wk4, and $wk5. I need to make it so that I can check if 1=2, 3, 4, 5 or if 2=3,4,5, etc. etc. I am trying to do it in a for loop, something like:
    for ($i = 0; $i < 5; $i++) {
    if (strcmp($wk1,$wk$i)) {
    echo "Match"
    }
    else if (strcmp($wk2,$wk$i)) {
    echo "Match"
    }
    Etcetera-etcetera
    }
    PHP:
     
    Jeremy1026, Aug 17, 2010 IP
  2. s_ruben

    s_ruben Active Member

    Messages:
    735
    Likes Received:
    26
    Best Answers:
    1
    Trophy Points:
    78
    #2
    Try this method:

    
    for ($i = 0; $i < 5; $i++) {
    $cmp_wk = "wk".$i;
    if (strcmp($wk1,$$cmp_wk)) {
    echo "Match"
    }
    else if (strcmp($wk2,$$cmp_wk)) {
    echo "Match"
    }
    Etcetera-etcetera
    }
    
    PHP:
     
    s_ruben, Aug 17, 2010 IP
  3. Jeremy1026

    Jeremy1026 Peon

    Messages:
    4
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    I actually ended up going a different way. I put the values of each $wkX into an array, and am using $i to get the value of the proper index and comparing against it.

    Thanks for your suggestion though, as a quick test shows that would have worked for me also.
     
    Jeremy1026, Aug 17, 2010 IP
  4. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #4
    Arrays are the proper way to do this anyway. You could also use a foreach() loop.

    www.php.net/foreach
     
    nico_swd, Aug 17, 2010 IP