Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    Regular Coder
    Join Date
    Dec 2006
    Posts
    417
    Thanks
    168
    Thanked 1 Time in 1 Post

    how to check if a string exists in an array?

    using PHP/mySQL combo

    if I SELECT a row from my table which looks like this for instance:

    Code:
    SELECT * FROM myCats WHERE userid=1
    
    userid  col2     col3     col4     col5  col6    col7
    1        hockey movies gaming  tv    music   fashion
    
    and store the results in an array (mysql_fetch_array)
    how do I then compare a string to see if it exists in the array or not?

    ie.:
    Code:
    if($myArray == 'hockey') {
      echo 'hockey is one of your selections';       
    }else{
       echo 'hockey isn't in your selections';
    }

  • #2
    Master Coder
    Join Date
    Dec 2007
    Posts
    6,682
    Thanks
    436
    Thanked 890 Times in 879 Posts
    Quote Originally Posted by Bobafart View Post
    using PHP/mySQL combo

    if I SELECT a row from my table which looks like this for instance:

    Code:
    SELECT * FROM myCats WHERE userid=1
    
    userid  col2     col3     col4     col5  col6    col7
    1        hockey movies gaming  tv    music   fashion
    
    and store the results in an array (mysql_fetch_array)
    how do I then compare a string to see if it exists in the array or not?

    ie.:
    Code:
    if($myArray == 'hockey') {
      echo 'hockey is one of your selections';       
    }else{
       echo 'hockey isn't in your selections';
    }
    PHP Code:
    if(in_array('hokey',$myarray)){
      echo 
    'hockey is one of your selections';
    }else{
       echo 
    'hockey isn\'t in your selections';

    I don't test this, if in_array don't work, could be because mysql_fetch_array is a hash array and I don't know how in_array work with this, you can use instead, array_search with same syntax.

    best regards
    Last edited by oesxyl; 01-25-2008 at 08:05 PM.

  • #3
    Regular Coder
    Join Date
    Apr 2006
    Posts
    231
    Thanks
    9
    Thanked 1 Time in 1 Post
    I looked at oesxyl code, and it seems ingeneous. I would have taken the info and put it in an array. Then run a simple index (for) loop from ur first array, to the last (colx) since x is the changing variable. If it matches with one of those, you are good.


  •  

    Posting Permissions

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