more efficient way to do this?

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
commissioner
Forum Newbie
Posts: 2
Joined: Thu Feb 19, 2009 12:44 am

more efficient way to do this?

Post by commissioner »

I have a really basic script, it works, however I know there's a more efficient way to write it.

For example:

Code: Select all

 
if($weapon[6] == 52){
$attack=50;
$defense=50;
}elseif($weapon[6] == 51){
$attack=40;
$defense=40;
}elseif($weapon[6] == 50){ ...etc
 
Basically its taking a chunk value and finding its attack and defense value. The only problem is it has to go down a huge list of weapons and compare each value until it finds the correct one.
So basically what I want to do is associate some numbers with different $attack and $defense values, so the script will jump straight to the assigned value. If that's even possible.

When I searched the forum I found a bit about associative arrays. I think that might be my solution but I'm not sure.

I'll keep researching this, but any point in the right direction will be very helpful.
Thanks,
-C
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Re: more efficient way to do this?

Post by Benjamin »

Yeah, arrays would do the job perfectly. For instance:

Code: Select all

 
<?php
$foo = array(
  '52' => array('attack' => 50, 'defense' => 50),
  '53' => array('attack' => 51, 'defense' => 51),
  '54' => array('attack' => 52, 'defense' => 52),
  '55' => array('attack' => 53, 'defense' => 53),
  // etc...
);
 
if (isset($foo[$weapon[6]])) {
    $attack  = $foo[$weapon[6]]['attack'];
    $defense = $foo[$weapon[6]]['defense'];
} else {
    // $weapon[6] is not in the array
}
 
commissioner
Forum Newbie
Posts: 2
Joined: Thu Feb 19, 2009 12:44 am

Re: more efficient way to do this?

Post by commissioner »

thank you, i really appreciate it :o
Post Reply