Page 1 of 1

my script is doing something it shouldnt

Posted: Sat Nov 01, 2003 11:20 am
by nemode
heya this is my script:
<table width=100% cellpadding=0 cellspacing=0 border=0>
<?php
echo( ucwords("<font size=4><b> $search</b></font><br><br>") );
$handle = @opendir( 'courses/' ) ;
$matches = array();

if ( $handle != '' ) {
while ( $file = readdir($handle)) {
if(strstr($file, $search)){
$matches[] = $file;
}
}
}
if( count($matches) == 0 )
echo('No course found. Please try again. If your search looked anything like this: Chinese level 1. Please simplify to: chinese.');
else
for($i = 0; $i <= count($matches); ++$i){

$color = "#336699";
if($i % 2 == 0)
$color = "#003366";
echo "<tr><td bgcolor=$color><font color=white>";
include( $matches[$i] );
echo "</font></td></tr>";
}
$i = 0;
if($i == count($matches) ){
die();
}
?>
</table>

basicly it searches for a word in a directory then displays each of the relevent files in an altenating color table. it does all right, but after ever search at the bottom of the page it displays:
Warning: main(): Failed opening '' for inclusion (include_path='./') in /data/hosted/nemode/mum/courses/course_search.txt on line 23
line 23 is: include( $matches[$i] );

anyone no y?

Posted: Sat Nov 01, 2003 12:23 pm
by pootergeist
<= count($matches) should just be < count($matches)

count() counts the number of elements - ie a[0],a[1],a[2] would be 3
arrays *generally* start at [0], so the last array element would be one less than count - eg a[2] is one less than 3

also note: putting count() within the second parameter of a for loop means it is evaluated every step - php does count($matches) once for every file - a better approach is to put it in the first parameter

for($i = 0, $j = count($matches); $i < $j; $i++) {

Posted: Sat Nov 01, 2003 12:34 pm
by nemode
cheers! it all works fine now!