strpos is not matching

2019-08-02 21:38发布

问题:

I want search one string and get related values, but in test the function, in each times search words(Title Or Would Or Post Or Ask) displaying(give) just one output Title,11,11 !!!! how can fix it?

  // test array
  $arr = array('Title,11,11','Would,22,22','Post,55,55','Ask,66,66');
  // define search function that you pass an array and a search string to
  function search($needle,$haystack){
    //loop over each passed in array element
    foreach($haystack as $v){
      // if there is a match at the first position
      if(strpos($needle,$v) == 0)
        // return the current array element
        return $v;
    }
    // otherwise retur false if not found
    return false;
  }
  // test the function
  echo search("Would",$arr);

回答1:

The issue lies in strpos. http://php.net/manual/en/function.strpos.php
The haystack is the first argument and the second argument is the needle.
You should also do a === comparison for getting 0.

// test array
$arr = array('Title,11,11','Would,22,22','Post,55,55','Ask,66,66');
// define search function that you pass an array and a search string to
function search($needle,$haystack){
  //loop over each passed in array element
  foreach($haystack as $v){
    // if there is a match at the first position
    if(strpos($v,$needle) === 0)
      // return the current array element
      return $v;
  }
  // otherwise retur false if not found
  return false;
}
// test the function
echo search("Would",$arr);


回答2:

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0 or "". Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

Source: http://php.net/strpos



回答3:

change this check:

// if there is a match at the first position
if(strpos($needle,$v) == 0)
  // return the current array element
  return $v;

to

// if there is a match at the first position
if(strpos($needle,$v) === 0)
  return $v;

or

// if there is a match anywhere
if(strpos($needle,$v) !== false)
  return $v;

strpos returns false if the string isn't found, but checking for false == 0 gives true, because php treats 0 as false. to prevent this, you'll have to use the === operator (or !==, depending on what exactly you're trying to do).