views:

85

answers:

3

A school system has 30 schools. The lowest school code is 298 and the highest is 516. For every school, the same processes will be called. The approach I've taken so far can be seen below. How can I shorten this code? Thank you.

for ( $i = 298; $i <= 516; $i++ )
{
   switch ( $i )
   {
      case 298:
         $c_sch = strval ( $i ) ;
         // call a function
         uf_mem_requester ( $c_sch, $t_mem1, $t_mem2, $t_mem3,
                            $d_year, $d_datadate ) ;
      case 303:
         // etc....etc.....
      case 309:
         // etc....etc.....
      default:
   }
}
+10  A: 

Not sure I understand. Is the switch because some IDs between 298 and 516 don't exist?

In that case, I would prefer

$school_ids = array(
  298, 300, 304, 312, 319, 320, 321, ....... all school IDs that actually exist
);

foreach (school_ids as $school) // a list of all IDs that exist
{
  $c_sch = strval ( $school ) ;
  uf_mem_requester ( $c_sch, $t_mem1, $t_mem2, $t_mem3, d_year, $d_datadate);
}
Pekka
+1 for beating me to it...
Lex
+1 Don't iterate unnecessarily.
BoltClock
and another for the same reason :-)
GrandmasterB
Well, darn, that is a heck of a lot more terse and reasonable than my attempt, which was not working, actually. Thank you for the ultra-fast response.
dave
ultra fast response.....grrrr...ask another question...I want a rematch :D +1
CrazyJugglerDrummer
+1  A: 
$schoolCodes = array(304, 313 /* etc */ );
foreach($schoolCodes as $code {
     $c_sch = strval ( $code ) ;
     // call a function
     uf_mem_requester ( $c_sch, $t_mem1, $t_mem2, $t_mem3,
                        $d_year, $d_datadate ) ;
}

Is that what you meant?

MrSoundless
beaten by Pekka
MrSoundless
Well, not what I meant, but exactly what I needed. Thanks.
dave
+1  A: 

Make an array of the school codes:

$schoolCodes =  array( 298, 303, 309 ...... );
foreach( $schoolCodes as $code ) {
    $c_sch = strval ( $i ) ;
    uf_mem_requester ( $c_sch, $t_mem1, $t_mem2, $t_mem3, $d_year, $d_datadate ) ;
    //and so forth...
}

This has the exact same effect of iterating through the codes, but its more efficient because you don't need to loop through any values you don't need to, and its much easier to update the codes through an array that through conditionals. :D

CrazyJugglerDrummer