[PHP] 'if' question

Discussion in 'Web Design & Coding' started by Glaanieboy, Feb 5, 2004.

  1. Glaanieboy

    Glaanieboy Moderator

    Messages:
    2,626
    Location:
    The Netherlands
    I currently have a if statement like this:
    Code:
    if ($host2 == "co" || $host2 == "org" || $host2 == "net" || $host2 == "ac"){
    As you can see, $host2 can be different values, if it is one of those values, then it should do something. It all works perfectly, but I have to add more '$host2 == "value" ' thingies there and I am afarid the list is going to be too long. I know that I can put all those values in a array, but how can I check those values with an 'if'?
     
  2. Khayman

    Khayman I'm sorry Hal... Political User Folding Team

    Messages:
    5,518
    Location:
    England
    You could do a switch statment

    Code:
    switch($host2)
    {
    case "co":
       //do blah
       break;
    case "org":
     //more blah
       break;
    case "net":
       //blah balh
       break;
    }
    
    can keep doing that forever
     
  3. Khayman

    Khayman I'm sorry Hal... Political User Folding Team

    Messages:
    5,518
    Location:
    England
    Or using an array

    Code:
    $valuestomatchon = array('co','org,'net','ac');
    
    $count = array_count_values(($valuestomatchon);
    for ($i = 0; $i < $count; $i++) 
    {
     if ($host2 == valuestomatchon[count])
     //do somthing
    }
    
    
    
     
  4. Glaanieboy

    Glaanieboy Moderator

    Messages:
    2,626
    Location:
    The Netherlands
    Let me give the part of the script I am talking about:
    Code:
    if ($host2 == "co" || $host2 == "org" || $host2 == "net" || $host2 == "ac"){
     $host = "$host1.$host2.$host3";
    }else{
     $host = "$host2.$host3";
    }
    As you can see, when it has found of those values, it makes a different $host than when those values aren't found. It doesn't matter if it's "co" or "org", it does the same. Only until $host2 doesn't contain one of those values, the other part is being executed.
    I hope I am making sense here.

    edit: Yes, that array example you gave is good. I will use that.
     
  5. Khayman

    Khayman I'm sorry Hal... Political User Folding Team

    Messages:
    5,518
    Location:
    England
    i found a better way
    Code:
    $valuestomatchon = array('co','org,'net','ac');
    
    if (in_array($host2, $valuestomatchon)) 
    {
    echo "Found it"
    }
    
    
     
  6. Glaanieboy

    Glaanieboy Moderator

    Messages:
    2,626
    Location:
    The Netherlands
    Thanks ;) *must learn how to use the PHP functions list*

    edit: Works perfectly ;)