如何检查数组中是否存在变量


How Can I Check To See If A Variable Exists In An Array?

我有一个名为data.txt的平面文件。每行包含四个条目。

数据.txt

blue||green||purple||primary
green||yellow||blue||secondary
orange||red||yellow||secondary
purple||blue||red||secondary
yellow||red||blue||primary
red||orange||purple||primary

我尝试这样做来找出变量"yellow"是否存在为任何行上的第一个条目:

$color = 'yellow';
$a = array('data.txt');
 if (array_key_exists($color,$a)){
 // If true
   echo "$color Key exists!";
   } else {
 // If NOT true
   echo "$color Key does not exist!";
   }

但它没有按预期工作。我可以更改什么来实现这一目标?谢谢。。。。

下面使用 preg_grep ,它对数组的每个元素(在本例中为文件的行)执行正则表达式搜索:

$search = 'yellow';
$file = file('file.txt');
$items = preg_grep('/^' . preg_quote($search, '/') . ''|'|/', $file);
if(count($items) > 0)
{
   // found
}
$fh = fopen("data.txt","r");
$color = 'yellow';
$test = false;
while( ($line = fgets($fh)) !== false){
    if(strpos($line,$color) === 0){
        $test = true;
        break;
    }
}
fclose($fh);
// Check $test to see if there is a line beginning with yellow

行:

$a = array('data.txt');

仅创建一个包含一个值的数组:"data.txt"。 在检查值之前,您需要先读取和分析文件。

好吧,这不是您将单独的数据列表从文本文件加载到数组中的方式。

此外,array_key_exists()只检查键,而不检查数组的值。

尝试:

$lines = file('data.txt', FILE_IGNORE_NEW_LINES);
$firstEntries = array();
foreach ($lines as $cLine) {
   $firstEntries[] = array_shift(explode('||', $cLine));
}
$colour = 'yellow';
if (in_array($colour, $firstEntries)) {
   echo $colour . " exists!";
} else {
   echo $colour . " does not exist!";
}

文件中的数据未加载到 $a 中。尝试

$a = explode("'n", file_get_contents('data.txt'));

加载它,然后检查每一行:

$line_num = 1;
foreach ($a as $line) {
   $entries = explode("||", $line);
   if (array_key_exists($color, $entries)) {
      echo "$color Key exists! in line $line_num";
   } else {
      echo "$color Key does not exist!";
   }
   ++$line_num;
}