处理字符串时,in_array() 上警告第二个参数的数据类型错误


Warning on in_array() for Wrong datatype for second argument, when working with strings

我使用此代码读出文件,我在 in_array() 上收到错误警告,因为第二个参数的数据类型错误。

if (isset($_POST['submit'])) {
  $SongToAdd = stripslashes($_POST['SongName']) . "'n";
  $ExistingSongs = array();
  if (file_exists("SongOrganizer/songs.txt") && filesize("SongOrganizer/songs.txt") > 0) {
    $ExistingSongs = file("SongOrganizer/songs.txt");
  }
}
if (in_array($SongToAdd, $ExistingSongs)) {
  echo "<p>The song you entered already exists!<br />'n";
  echo "Your song was not added to the list.</p>";

该文本文件包含:

Bang Bang
Doctor
Hello
Ice Cream Man
Show Me
Doctor

那么,你的页面第一次加载时呢?如果未设置$_POST['submit'],则将$ExistingSongs nullin_array抱怨是对的。

如果你在启用所有错误的情况下进行开发 - 使用error_reporting(E_ALL | E_STRICT)或通过php.ini完成 - 那么你也会得到一个关于$ExistingSongs是一个未定义的变量的通知。

如果未设置$_POST['submit']变量,则$ExistingSongs变量保持未定义状态,则可能会导致警告。

条形斜杠期望一个字符串作为输入,并输出一个字符串:http://php.net/stripslashes

当你调用in_array()时,$SongToAdd是一个字符串,因此你的错误。