help exactly matching one element in a multi-element field

Discussion in 'PHP' started by phantom, Oct 19, 2007.

  1. #1
    I have a field with numbers separated by '|' like 9|10|106|26|

    What I need to do is check to see if just one of those numbers is an exact match to a variable $userid and if it is print something.
    Obviously 10 would need to match whereas 106 does not....or...in other words 26 is different than 226....( I hope you guys get what I mean if not I'll try to explain better)


    Here is the NON working code I have so far:


    
    $getids =mysql_query("select numbers from users where Username='$username'; ") or die ("could not get id info");
    $idstotal = mysql_fetch_array($getids);
    
    $idnums = explode('|',$idstotal['numbers']);
    
    foreach(explode('|',$idstotal['numbers']) as $value) {
       if($value == $userid) {
    $i ='[F]';
       }
    else {
    $i ="[A]";
    }
    }
    
    echo $1;
    
    Code (markup):
    So far it does not work because $userid never matches because the numbers come out all together as one single number. I just can't figure out how to get them all to be compared individually.

    Can you guys help me to get it to work?
     
    phantom, Oct 19, 2007 IP
  2. theOtherOne

    theOtherOne Well-Known Member

    Messages:
    112
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    108
    #2
    You don't need to put explode('|',$idstotal['numbers']); as a condition in foreach, as you already defined a variable for that. I replaced it with $idnums.
    Also, the last row said echo $1;, although you stored F/A in $i - fixed that too ;)

    EDIT: Found another thing... the code would only have worked if the matching element is the last element in the list. So, when you find a match, you have to break the loop. Otherwise $i would be overwritten and your result is lost. => I added a break to the code.

    
    $getids =mysql_query("select numbers from users where Username='$username'; ") or die ("could not get id info");
    $idstotal = mysql_fetch_array($getids);
    
    $idnums = explode('|',$idstotal['numbers']);
    
    foreach($idnums as $value) {
       if($value == $userid) {
          $i ='[F]';
          break;
       }
       else {
          $i ="[A]";
       }
    }
    
    echo $i;
    
    PHP:
     
    theOtherOne, Oct 19, 2007 IP
  3. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #3
    How about:
    
    $i = in_array($userid, $idnums) ? '[F]' : '[A]';
    
    PHP:
     
    nico_swd, Oct 20, 2007 IP
  4. phantom

    phantom Well-Known Member

    Messages:
    1,509
    Likes Received:
    32
    Best Answers:
    0
    Trophy Points:
    140
    #4
    Great! Thanks guys..........
     
    phantom, Oct 20, 2007 IP