Question about loops

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
auaero
Forum Newbie
Posts: 9
Joined: Wed Aug 28, 2002 9:47 am

Question about loops

Post 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
User avatar
nielsene
DevNet Resident
Posts: 1834
Joined: Fri Aug 16, 2002 8:57 am
Location: Watertown, MA

Post 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.
User avatar
Takuma
Forum Regular
Posts: 931
Joined: Sun Aug 04, 2002 10:24 am
Location: UK
Contact:

Post by Takuma »

If you think the question is "dumb" you should not ask! And a question is never can be a dumb question!
Post Reply