Stripos找不到值

时间:2019-12-13 20:39:29

标签: php php-7

正如您在输出中看到的,stripos无法捕获_formtoken值,任何人都可以通过解决方案向我解释它:

$value = ['_formtoken','expiry','version','pan','expiry','purchAmount','_formtoken','pan'];
for($i=0;$i<count($value);$i++){

  if (stripos($added, $value[$i]) == false) { 
      echo $value[$i] . ' => Not exists in <br>';    
      $added .= $value[$i];
  } 
  else { 
          echo $value[$i] . ' => already exists  <br>'; 
  } 

}

输出:

_formtoken => Not exists in
expiry => Not exists in
version => Not exists in
pan => Not exists in
expiry => already exists
purchAmount => Not exists in
_formtoken => Not exists in
pan => already exists 

2 个答案:

答案 0 :(得分:1)

stripos可能返回0或false。如果您要搜索的字符串位于搜索字符串的开头,则它将返回0。如果在if语句中使用该字符串,则其结果将为false。要解决此问题,请使用===

$value = ['_formtoken','expiry','version','pan','expiry','purchAmount','_formtoken','pan'];
$added = null;
for($i=0;$i<count($value);$i++){
  $pos = stripos($added, $value[$i]);
  if ( $pos === false) { 
      echo $value[$i] . ' => Not exists in <br>' . "\n";    
      $added .= $value[$i];
  } 
  else { 
      echo $value[$i] . ' => already exists  <br>'."\n"; 
  } 
}

运行它时,这是我看到的输出。

_formtoken => Not exists in <br>
expiry => Not exists in <br>
version => Not exists in <br>
pan => Not exists in <br>
expiry => already exists  <br>
purchAmount => Not exists in <br>
_formtoken => already exists  <br>
pan => already exists  <br>

答案 1 :(得分:-1)

似乎您正在尝试为数组中每个唯一值创建一个字符串,对吗?如果是这样,请尝试使用此方法,它会更清洁:

$inputArray = ['_formtoken', 'expiry', 'version', 'pan', 'expiry', 'purchAmount', '_formtoken', 'pan'];

// Only keep the first occurrence of each value
$uniqueInputArray = array_unique($inputArray);

// Output the values separated by a single space between each
echo implode(' ', $uniqueInputArray);

或作为一行:

echo implode(' ', array_unique(['_formtoken', 'expiry', 'version', 'pan', 'expiry', 'purchAmount', '_formtoken', 'pan']));