开发者

Sorting through a delimited string with PHP

I am trying to create a script that checks if a certain value is in a comma delimited string, and if the value is present, it should return true else it should return false.

Basically, I am trying to check if a user has voted for a specific person before, and if so, they cannot vote again, if they have not, vote and then add their uid to the database.

I am using explode to get all the values into an array, but I am unsure about the checking function, I have a few ideas but this is quite an important script so I wanted to see if there is a better way of going about it.

$test = "john,jack,tom";

$exploded = explode(",",$test);

$hostID = "john";

foreach($exploded as $one){
    if($one == $hostID){
        $retu开发者_Go百科rn = TRUE;
    }else{
        $return = FALSE;
    };
};

Thanx in advance!


  • You could use in_array.
  • Some people prefer to use lowercase true and false.
  • The semicolon after } is not needed
  • $return = TRUE does not actually stop the function. Maybe you do return $return.
  • Some people like to put spaces after comma's and keywords (e.g. foreach, if, else)
  • Some people prefer single quotes over double quotes

Code:

function find_name($name, $list)
{
    $exploded = explode(',', $list);
    return in_array($name, $exploded);
}

var_dump(find_name('john', 'john,jack,tom'));
?>


As Sjoerd says, in his very good advice.

function find_name( $needle , $haystack ) {
  if( strpos( $haystack , $needle )===false )
    return false;
  return in_array( $needle , explode( ',' , $haystack ) );
}

Test cases:

// find_name( 'john' , 'peter,mark,john' );
true
// find_name( 'peter' , 'mark,john' );
false

EDITED: As per advice from Gordon.


You could also use

  • strpos — Find position of first occurrence of a string

instead:

 return strpos('john,jack,tom', 'barney'); // returns FALSE

Note that the function returns the position if the string was found, so searching for john will return zero, which would be FALSE if you compare it for equality (==). In other words use the identity comparator (===).

As Lucanos correctly points out, there is chance to get false positives when using strpos if the searched name is part of a longer name, e.g. searching for jean only would also find jean-luc. You could add a comma at the end of the haystack string and search for jean, though, but then again, it feels hackish. So it's likely better to use in_array.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜