Page 1 of 1

Question about loops

Posted: Wed Aug 28, 2002 11:11 am
by auaero
Okay guys, here's another dumb question:

I want to use a while loop to go dynamically change an array name and assign values to it (does that make any sense?). This will be used to go through a set of movie titles and pull out the ratings and assign the rating from each movie into an array called Rating. The movie titles and ratings are already stored in an array called movie.

$i = 1;
while ($i <= 9) {
if (ereg (" NC-17 ", $movie[$i], $Rating[$i]) {
print $Rating[$i];
} elseif (ereg (" R ", $movie[$i], $Rating[$i]) {
print $Rating[$i];
} elseif (ereg (" PG-13 ", $movie[$i], $Rating[$i]) {
print $Rating[$i];
} elseif (ereg (" PG ", $movie[$i], $Rating[$i]) {
print $Rating[$i];
} elseif (ereg (" G ", $movie[$i], $Rating[$i]) {
print $Rating[$i];
} else {
$Rating[$i] = "NR";
}
$i++;
}

Okay, so this obviously isn't right (it doesn't work) and I'm totally new to PHP. I know FORTRAN (old school, baby) and Java and this just seemed like the natural way to progam this loop. If anyone could be so kind as point me in the right direction, I'd be very grateful.

Thanks,
AUaero

Posted: Wed Aug 28, 2002 11:38 am
by nielsene
If I understand your problem, I think I would recode it like this.

Code: Select all

$ratings=array();
$ratingLabels=array("G","PG","PG-13","R","NC-17");
$numLabels = count($ratingLabels);
$numMovies = count($movies);
for ($i=0; $i<$numMovies;$i++) // don't know if you use 0/1 indexing, example code was 1-based
// but zero based in much more common, if you're new to PHP the 1 based might have been a mistake
&#123;
   $movie = $movies&#1111;$i];
   for ($j=0;$j<$numLabels;$j++)
   &#123;
       if (!(strpos($movie,$ratingLabels&#1111;$j])===FALSE))
       &#123;
            $ratings&#1111;$i]=$ratingLabels&#1111;$j];
            break;
       &#125;
   &#125;
   if ($ratings&#1111;$i]=="") $rating&#1111;$i]="NR";
&#125;
or something along those lines other will likely suggest a foreach version :) or twenty other equally good ways of doing it.

Posted: Wed Aug 28, 2002 4:14 pm
by Takuma
If you think the question is "dumb" you should not ask! And a question is never can be a dumb question!