Page 1 of 1

more efficient way to do this?

Posted: Thu Feb 19, 2009 1:08 am
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

Re: more efficient way to do this?

Posted: Thu Feb 19, 2009 1:27 am
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
}
 

Re: more efficient way to do this?

Posted: Thu Feb 19, 2009 1:37 am
by commissioner
thank you, i really appreciate it :o