2013-07-09 44 views
0

我有一些偶爾返回的代碼和「Undefined Offset 8」。爲什麼我偶爾會得到「Undefined Offset 8?」

我搜索了,我找不到「Undefined Offset」定義,使它更神祕。

下面的代碼:

while($lowest_plays !== $plays[$x]){ 
    $x = rand(0,count($plays)); 
} 

偏移發生在while循環,這似乎是這種特定的偏移通常發生。 $ lowest_plays和$ plays變量總是正常的,而當「Undefined Offset」發生時我看不到任何模式。

變量$x是在0$plays-1之間的隨機數。

以下是其中的「未定義偏移8」告示的值:

Plays: Array ([0] => 147 [1] => 147 [2] => 146 [3] => 147 [4] => 147 [5] => 146 [6] => 147 [7] => 146) 
Lowest Plays: 146 
Random variable ($): 1 
+0

最後一個數組的索引是'計數($陣列) - 1'。您在0和數組長度之間隨機化。但最後的指數<長度。 – mario

+0

請重新閱讀['rand()']的手冊頁(http://sg3.php.net/manual/en/function.rand.php#refsect1-function.rand-returnvalues)。 –

回答

3

數組零索引,以使陣列項$戲劇[0] ..高達$戲劇[7] 。 count是8 - 元素的總數。因此,你需要

$x = rand(0,count($plays) - 1); 

否則在你試圖讀取$plays[8]不存在的某個階段。

+0

是的,我明白了。我有'$ x = rand(0,count($ plays)-1);'在while循環之前,但之後沒有改變。好眼睛。首先我看到了這一點,就像是「我已經這樣做了」,然後我看到發生了什麼。謝謝!很有幫助。 – JVE999

1

$plays,你不必與任何索引條目8. rand功能包括$min$max所以你需要

$x = rand(0, count($plays)-1); 
1

你生成0和count($plays)之間的隨機數作爲索引使用到$戲劇[]。戲劇的大小是8元,但指數從0到7

你應該計算你randim號碼這樣的:

while($lowest_plays !== $plays[$x]){ 
    $x = rand(0,count($plays)-1); // random from 0 to 7 
} 
1

你有8個元素的數組中如此

rand(0, count($plays)) 

會給你一個從0到8的隨機整數;

如果它碰巧給你8,並且你試圖訪問$ plays [8],那就是錯誤所在。正確的方法:

rand(0, count($plays)-1) 
2

從你的問題引用:

變量$ x爲0和$戲劇之間的隨機數 - 1

如果這是真的,你不會有問題,但看看rand(min, max)的返回值,它表示(突出顯示我自己的):

min(或0)和max(或getrandmax(),,包括)之間的僞隨機值。

因此,正確的說法應該是:

$x = rand(0,count($plays) - 1); 
相關問題