【问题标题】:php txt string compare array comparephp txt 字符串比较 数组比较
【发布时间】:2025-12-23 15:30:06
【问题描述】:
$c = '4432';
$word = file_get_contents('1234.txt');
$value = explode(" ",$word);
for ($i = 0; $i < 3; $i++) {
   if ($value[$i] = $c){
      echo $value[$i];
      break;
    }
}

文件1234.txt内容:

1234 789 
4432 998
5532 999

如何分别比较 4432 和 789 的值?我需要:

if $c is 1234 then get 789 value
if $c is 4432 then get 998 value
if $c is 5532 then get 999 value

现在我的代码只能得到 1234 或 4432 或 5532。

谢谢。

【问题讨论】:

  • 如何比较4432和什么元素?大批?钥匙?价值?

标签: php string compare


【解决方案1】:

您可以尝试使用file()explode() 函数获得预期结果:

<?php
$match = '4432';

$file = file('1234.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($file as $line) {
    $words = explode(" ", $line);
    if ($words[0] == $match) {
        echo $words[1];
        break;
    }       
}
?>

补充说明:

  • 函数file_get_contents() 将整个文件读入一个字符串,但file() 将文件的内容返回到一个数组中。
  • Comparison operator 在 PHP 中是 == (===),而不是 =

【讨论】: