PHP检查行号x是否存在

时间:2014-03-12 17:47:35

标签: php arrays text-files lines

有没有办法检查线是否存在?如果存在行,则读取它

我的代码

<?php
$s = 7; //$_POST['s'];
$file = fopen("text.txt","r");
$lines = file("text.txt");
echo $lines[$s];
fclose($file);
?> 

text.txt只包含6行,因此返回 - 未定义的偏移量:7

1 个答案:

答案 0 :(得分:2)

$s = 7 - 1; // Arrays are zero-based in PHP
$lines = file("text.txt");
if (count($lines) >= $s) {
  // you're good
}

或:

$s = 7 - 1; // Arrays are zero-based in PHP
$lines = file("text.txt");
if (isset($lines[$s])) {
  // you're good
}