robinbell Posted January 25, 2009 Share Posted January 25, 2009 Hello,I'm trying to test if a given value is found within a string - I have a list of user names and want to test if a new user is already present in the list. I've tried with strrpos(string to be searched, search value) and this works OK (eg returns the position of the value in the string) but in this case, where my users present is "alan robin fred jim" if I search for "alan" I am returned a value of 0. This is correct, but 0 is treated as false when I test strrpos, so although the user is present, he is reported as not found.To get around this I have simply added a blank space to the string to be searched before calling strrpos, so that if the first name is found, strrpos returns 1 instead of 0, but this seems to be a strange way to get around the problem.My code looks like this: $sql="SELECT nick FROM chat_user where logged_in = 'Y' group by nick";$users = ' ';$nickname = $_GET['nickname'];$result = mysql_query($sql);while($row = mysql_fetch_array($result)){ $users .= $row['nick'] . " ";}$found = strrpos($users,$nickname);if ($found > 0){ echo 'Y';}else{ echo 'N';} There must be a better way! I want to use the 'Y' or 'N' back in a javascript to trigger an alert if the user is already logged on...Thanks anyone for suggestions Link to comment Share on other sites More sharing options...
jeffman Posted January 25, 2009 Share Posted January 25, 2009 Read the manual here: http://www.php.net/manual/en/function.strrpos.phpBasically, you want to use a true equality test (=== or !==) against false. Link to comment Share on other sites More sharing options...
justsomeguy Posted January 25, 2009 Share Posted January 25, 2009 strpos isn't really the best way to do that. If you have a user called "steve1", and you're checking for a user called "steve", strpos will say it exists. You should split up the usernames into an array and then use in_array to search for a value. Link to comment Share on other sites More sharing options...
robinbell Posted January 27, 2009 Author Share Posted January 27, 2009 Hi,Thanks for the help. I did read the manual, honest!I've now changed the script to create an array with the names and used in_array to check for a value, which works fine.Thanks again.... Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.