...

View Full Version : Problem with array



thomas55
01-14-2012, 08:10 PM
I have some code im trying to make smaller using a for loop and an array. I basically have a form with 4 drop down boxes that are either minor or substantial, if minor is selected 5 should be added to the total
if substantial 10 should be added for each drop down box. My original code that works is:



if($a1 == "Minor")
{
$count = $count + 5;
}
else if ($a1 == "Substantial")
{
$count = $count + 10;
}


if($b1 == "Minor")
{
$count = $count + 5;
}
else if ($b1 == "Substantial")
{
$count = $count + 10;
}

if($c1 == "Minor")
{
$count = $count + 5;
}
else if ($c1 == "Substantial")
{
$count = $count + 10;
}


if($d1 == "Minor")
{
$count = $count + 5;
}
else if ($d1 == "Substantial")
{
$count = $count + 10;
}


the new code which doesn't work is:



$letter = array(
0 => $a1 = $_POST['a1'],
1 => $b1 = $_POST['b1'],
2 => $c1 = $_POST['c1'],
3 => $d1 = $_POST['d1']
);

$x = 0;

for ($i = 0; $i < count($letter); $i++)
{
if($letter[$x++] == "Minor")
{
$count = $count + 5;
}
if ($letter[$x++] == "Substantial")
{
$count = $count + 10;
}
}

Im starting to think its not a problem with the array but some problem in the count. Any pointers in the right direction would be appreciated.

_Aerospace_Eng_
01-14-2012, 08:30 PM
Can you change your html to make your selects arrays? e.g. name="selections[]"

Inigoesdr
01-14-2012, 08:34 PM
You don't need that $x variable; you are incrementing it twice each loop and you already have a iterator variable defined by the for() (http://php.net/for) loop:


$letter_count = count($letter);
for ($i = 0; $i < $letter_count; $i++)
{
if($letter[$i] == 'Minor')
{
$count += 5;
}
elseif ($letter[$i] == 'Substantial')
{
$count += 10;
}
}



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum