访问数组索引时未定义的索引

时间:2016-06-12 11:41:09

标签: php arrays

我正在尝试修改用户计数器代码,该代码打印存储在数组中的消息。访问者计数器被视为数组索引

<?php
session_start();
$counter_name = "counter.txt";

$age = array("url1","url2","url3");
// Check if a text file exists. If not create one and initialize it to zero.
if (!file_exists($counter_name)) {
  $f = fopen($counter_name, "w");
  fwrite($f,"0");
  fclose($f);
}
// Read the current value of our counter file
$f = fopen($counter_name,"r");
$counterVal = fread($f, filesize($counter_name));
fclose($f);
$counterVal++;
$f = fopen($counter_name, "w");
fwrite($f, $counterVal);
fclose($f); 

echo "hi Hello";
echo $counterVal;   
$me = $age[$counterVal];
echo $me;
?>

但是我收到以下错误,

hi Hello1
PHP Notice:  Undefined index: 1
 in xxx/glob.php on line 23

可能的错误是什么,因为index 1有一个与之相关的值。

1 个答案:

答案 0 :(得分:0)

更好的代码:

<?php
session_start();
$counter_name = "counter.txt";
$age = array("url1","url2","url3");
$counterVal = file_exists($counter_name)?
    (int)file_get_contents($counter_name)++:
    0;
file_put_contents($counter_name, $counterVal);

echo "hi Hello";
echo $counterVal;   
$me = $age[$counterVal];
echo $me;

&GT;

相关问题