Forum Moderators: coopster

Message Too Old, No Replies

Help with a php notice.

help!

         

Zenden

10:51 pm on Mar 25, 2005 (gmt 0)

10+ Year Member



i have the following code,


<?php
/* Made by Zenden */
$players = "C:\otserv\players";
$i = 0;
$x = array();
$dir = dir($players);
while($plik = $dir->read()){
if (eregi(".xml$",$plik)){
$file = file($players."/".$plik);
$file = explode('"',$file[1]);
$plik = explode(".",$plik);
$x[$i] = $file[13]." <strong>Name:</strong> ".$plik[0];
$i++;
}
}
SORT($x, 1);
while ($i >= 0){
echo $x[$i]."<b><br><strong> Level: </strong></b>";
$i = $i - 1;
}
?>

but when i open it i get the following error
Notice: Undefined offset: 493 in c:\apache group\apache\htdocs\a.php on line 18

it doesnt intervenes in the prupose of the code.

all i want is to take it off there.
can someone help me?

jatar_k

2:13 am on Mar 26, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Welcome to WebmasterWorld Zenden,

hmm offset 493, are there only 492 elements in the array? is spitting out an empty one at the end?

maybe instead of while ($i >= 0){ you need something like
while ($i >= 0 and isset($x[$i])){

I am not sure as I have not really looked too much at what the code does, just a thought.

Salsa

5:42 am on Mar 26, 2005 (gmt 0)

10+ Year Member



I think that Jatar is on the right track, except that there appear to be 493 elements (indexes 0-492)
;)
The problem is that the first while loop increments $i even after processing the last element of $x, creating a later index for a nonexistent element. Jatar's fix should work, but I think it might be cleaner to decrement $i by one ($i--) after the first while loop because you know that the first while loop will always make $i equal to one greater than you want it.

To think of it another way, before you get out of the first while loop, you must increment $i until it is false. (Even after the last element is assigned to $x, $i is incremented by one.) So it is then necessary to decrement $i to a value that is true before you use it in the next while loop.

I hope this helps.

coopster

1:13 pm on Mar 26, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Now that you understand what is happening, perhaps you want to consider the for [php.net] control structure as opposed to while [php.net]? Quite handy for these types of operations. Also, I like to count [php.net] the values in the array I am processing rather than rely on the *last* value that was in the supposed index:
for ($i = count($x)-1; $i >= 0; $i--) { 
echo $x[$i]."<b><br><strong> Level: </strong></b>";
}