Page 1 of 1
simplifying code using OOP
Posted: Thu Jul 03, 2003 10:58 am
by fariquzeli
I am doing a script that will return a 1 or a 2 depending on the state the person puts in a form. I want 25 states to return a 1, and the other 25 to return a 2.
Now rather than do it like this:
Code: Select all
<?php
if ($zone_id == "IL" || $zone_id == "IN" || $zone_id =="OK" || $zone_id == "OR") {
$vendor_code = "1";
}
else {
$vendor_code = "2";
}
?>
I only did 4 states above as you can see, but I will end up doing 25, is there an easier way to do this?
Posted: Thu Jul 03, 2003 11:03 am
by m3mn0n
Using
switch() mixed with looping through a database or array for the states of each of the two types...i'd do it that way. It's not really OOP but it works.

Posted: Thu Jul 03, 2003 11:11 am
by choppsta
Presuming that the state is picked from a select box...
Why not get the HTML form to do the work:
E.g.
<option value="1">IL</option>
..etc..
Posted: Thu Jul 03, 2003 11:11 am
by Stoker
or in this case I would think that an array and in_array would be more efficient...
Code: Select all
<?php
$code = array(
# Continental US
1 => array ('IL','NY','OH','MN','Etc'),
# Islands US
2 => array ('HI','AK');
# Canada
3 => array ('ON','Etc..');
);
$myzone = 9; # Default if none found
foreach ($code as $zone => $members)
{
if (in_array($_REQUEST['state'], $members))
{
$myzone = $zone;
break; # Exit loop
}
}
?>
Posted: Thu Jul 03, 2003 11:13 am
by m3mn0n
Precisely.

Posted: Thu Jul 03, 2003 11:20 am
by fariquzeli
Thanks a bunch,
the state doesn't come from a drop down but the built in error checking makes sure it is put in as either State, or ST (Illinois or IL)
-timmy