Log in

View Full Version : Undefined Offset?



alexjewell
10-16-2007, 11:05 PM
Hey, I'm trying to pull 15 random images from a directory and display them. There are always 15 images that are attempted to display, but there is always at least 1 image displayed without a source, and therefore less than 15 actual images show up. You can see the massacre here: http://www.alexjewell2.com/clients/quinn/tickerIdea.php

Below is my code:



$dirpath = 'imgs/gallery/t/';
$dh = opendir($dirpath);
$i = 0;

while ($f = readdir($dh)) {
if ($f =='.'||$f=='..') { continue; }
if (!@getimagesize($dirpath.$f)) { continue; }
$imgs[$i]=$f;
$i++;
}
$st = (count($imgs)>=15)?15:count($imgs);
for ($n=$st;$n>0;$n--) {
$r = mt_rand(0,count($imgs));
echo '<a href="gal.php?file='.$imgs[$r].'"><img src="'.$dirpath.$imgs[$r].'" /></a>';
ksort($imgs);
unset($imgs[$r]);
}


Any ideas on what undefined offset means and why line 34, unset($imgs[$r]);, is causing so much trouble? And if line 34 isn't the issue, what is? Thanks.

alexjewell
10-17-2007, 01:23 AM
Alright, after some recoding, I've solved the issue:



$dirpath = 'imgs/gallery/t/';
$dh = opendir($dirpath);

while ($f = readdir($dh)) {
if ($f == '.' || $f == '..') {}
else {
if (@getimagesize($dirpath.$f)) {
$imgs[] = $f;}
else {}
}
}

for($i=0; $i<15; $i++) {
shuffle($imgs);
$this_img = array_pop($imgs);
echo '<a href="gal.php?file='.$this_img.'"><img src="'.$dirpath.$this_img.'" /></a>';}


The only thing I could improve would be the while statement...I could probably clean it up a bit. If anyone has any ideas, let me know. If not, it's at least working now. Thanks.

boogyman
10-17-2007, 12:51 PM
while ($f = readdir($dh)) {
if ($f != '.' || $f != '..') {
if (@getimagesize($dirpath.$f)) {
$imgs[] = $f;
}
}
}


if you need to you can add the other conditions, since you only have 1 condition I would test for that condition and not worry about the rest, because it will just add time/bandwidth usage/storage against your account

djr33
10-17-2007, 06:12 PM
while ($f = readdir($dh)) {
if (@getimagesize($dirpath.$f)) {
$imgs[] = $f;
}
}
That is simpler and probably faster, though I might keep the check to be sure it isn't . or .. because those are specifically never used, so it's a good habit, AND it might be slow to use getimagesize on those, so you could end up saving some time. Not really sure on that.

It would save processing time and CPU usage, but no bandwidth (same output) nor storage (sans the 23+ character difference in the code, though that would easily be compensated for by removing whitespace).