2016-06-12 78 views
0

我試圖修改用戶計數器代碼,該代碼打印存儲在數組中的消息。訪客計數器被作爲數組索引訪問數組索引時未定義的索引

<?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有與之asociated值。

回答

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; 

>

+0

如果連你的代碼工作正常,這是不明確的,你改變了什麼,以及爲什麼OP代碼不工作 – splash58