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
Question about loops
Moderator: General Moderators
If I understand your problem, I think I would recode it like this.
or something along those lines other will likely suggest a foreach version
or twenty other equally good ways of doing it.
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
{
$movie = $moviesї$i];
for ($j=0;$j<$numLabels;$j++)
{
if (!(strpos($movie,$ratingLabelsї$j])===FALSE))
{
$ratingsї$i]=$ratingLabelsї$j];
break;
}
}
if ($ratingsї$i]=="") $ratingї$i]="NR";
}