Php 如何检查数组中是否存在变量?
我有一个名为data.txt的平面文件。每行包含四个条目 data.txtPhp 如何检查数组中是否存在变量?,php,arrays,Php,Arrays,我有一个名为data.txt的平面文件。每行包含四个条目 data.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”是否作为任何行的第一个条目存在: $co
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!";
}
但它并没有像预期的那样发挥作用。我能做些什么来让这一切继续下去?谢谢……文件中的数据未加载到
$a
中。试一试
$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 = 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;
}
该行:
$a = array('data.txt');
仅创建包含一个值的数组:“data.txt”。在检查值之前,您需要先读取并解析文件。好吧,这不是将文本文件中的单独数据列表加载到数组中的方式 另外,
array\u key\u exists()
只检查键,不检查数组的值
尝试:
以下代码利用,它对数组的每个元素(在本例中为文件的行)执行正则表达式搜索:
此代码显示:警告:explode()需要至少2个参数,第10行的/www/tests/mobilestimulus/array_tests/index1.php中给出了1个警告:为第10行的/www/tests/mobilestimulus/array_tests/index1.php中的foreach()提供的参数无效13@mobilestimulus我没有测试就写了这段代码。我错过了第一次分解的第一个参数分隔符(“\n”-新行字符)。现在应该可以正常工作了。即使黄色不是行中的第一个条目,此代码也会返回“exists”。@mobilestimulus:没有注意到“first”“约束,我将更新它。尽管这将与其他单词的任何前缀匹配为假阳性。如果这个例子是虚构的。例如,
$search='yell'
将匹配黄色
作为第一个单词,需要对正则表达式进行更改,以确保后面有分隔符或行终端。@Orbling:感谢您的忽略。更新。
$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!";
}
$search = 'yellow';
$file = file('file.txt');
$items = preg_grep('/^' . preg_quote($search, '/') . '\|\|/', $file);
if(count($items) > 0)
{
// found
}