JVE999
JVE999

Reputation: 3517

Why do I occasionally get "Undefined Offset 8?"

I have a bit of code that occasionally returns and "Undefined Offset 8."

I searched and I can't find the "Undefined Offset" definitions, making it more mysterious.

Here's the code:

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

The offset occurs on the while loop, which seems to be where this particular offset usually occurs. The $lowest_plays and $plays variables are always normal and I don't see any pattern for when the "Undefined Offset" occurs.

The variable $x is a random number between 0 and $plays-1.

Here are the values for one of the "Undefined Offset 8" notices:

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

Upvotes: 1

Views: 4966

Answers (5)

Ja͢ck
Ja͢ck

Reputation: 173642

Quoted from your question:

The variable $x is a random number between 0 and $plays - 1.

If that were true, you wouldn't have a problem, but looking at the return value of rand(min, max), it states (highlights my own):

A pseudo random value between min (or 0) and max (or getrandmax(), inclusive).

Therefore, the correct statement should be:

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

Upvotes: 2

David Lin
David Lin

Reputation: 13353

You have 8 elements in the array so

rand(0, count($plays))

will give you a random integer from 0 to 8;

if it happen to give you the 8, and you try to access $plays[8], that's where the error is about. The correct way:

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

Upvotes: 1

user1864610
user1864610

Reputation:

You are generating a random number between 0 and count($plays) to use as an index into $plays[]. The size of plays is 8 elements, but the indexes run from 0 to 7.

You should be calculating your randim number like this:

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

Upvotes: 1

apartridge
apartridge

Reputation: 1820

In $plays, you do not have any entry with index 8. The rand function includes both $min and $max so you need

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

Upvotes: 1

Andy G
Andy G

Reputation: 19367

Arrays are zero-indexed, so the array items are $plays[0].. upto $plays[7]. count is 8 - the total number of elements. So you need

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

otherwise at some stage you are attempting to read $plays[8] which doesn't exist.

Upvotes: 5

Related Questions