simplifying code using OOP

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
fariquzeli
Forum Contributor
Posts: 144
Joined: Mon Jun 24, 2002 9:16 am
Location: Chicago
Contact:

simplifying code using OOP

Post 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?
User avatar
m3mn0n
PHP Evangelist
Posts: 3548
Joined: Tue Aug 13, 2002 3:35 pm
Location: Calgary, Canada

Post 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. :)
choppsta
Forum Contributor
Posts: 114
Joined: Thu Jul 03, 2003 11:11 am

Post 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..
User avatar
Stoker
Forum Regular
Posts: 782
Joined: Thu Jan 23, 2003 9:45 pm
Location: SWNY
Contact:

Post 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
   }
}

?>
User avatar
m3mn0n
PHP Evangelist
Posts: 3548
Joined: Tue Aug 13, 2002 3:35 pm
Location: Calgary, Canada

Post by m3mn0n »

Precisely.

8)
fariquzeli
Forum Contributor
Posts: 144
Joined: Mon Jun 24, 2002 9:16 am
Location: Chicago
Contact:

Post 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
Post Reply