View Full Version : multiply arrays

11-06-2007, 02:50 AM
Hello, I have had no luck finding an answer to this question on either CodingForums or Google. All I want to do is multiply values from 2 arrays together. The first array contains a pricing list, the second array contains quantities entered by a user. The arrays are as follows:

$prices = array(1 => 35, 25, 10, 30, 20, 8, 60, 50, 12, 55, 45, 10, 50, 35, 14, 40, 30, 12, 20, 2, 6, 20);
$quantity = array(1 => $_SESSION['a2dfam'], $_SESSION['a2dinv'], $_SESSION['a2dstu'], $_SESSION['a1dfam'], $_SESSION['a1dinv'], $_SESSION['a1dstu'], $_SESSION['na2dfam'], $_SESSION['na2dinv'], $_SESSION['na2dstu'], $_SESSION['na1dfam'], $_SESSION['na1dinv'], $_SESSION['na1dstu'], $_SESSION['dec2dfam'], $_SESSION['dec2dinv'], $_SESSION['dec2dstu'], $_SESSION['dec1dfam'], $_SESSION['dec1dinv'], $_SESSION['dec1dstu'], $_SESSION['banquet'], $_SESSION['pizza'], $_SESSION['brunch'], $_SESSION['dues']);

I want to multiply each array value in $prices with the corresponding array value in $quantity in order to create a third array ($total). Also, if $quantity is not set, then I don't want to set the corresponding position in $total.

The only option I've found is to use the array_walk function, but this doesn't seem ideal.

Any advice?


11-06-2007, 03:45 AM
Remove the 1 => from the array and just loop over it:
$total = array();
for($i = 0; $i < count($quantity); $i++)
$total[] = $quantity[$i] * $prices[$i];
This is just an example.

11-06-2007, 03:45 AM
No need to reply, it was too simple:

for ($i=1; $i<=22; $i+=1) {
$total[$i] = $prices[$i]*$quantity[$i];

11-06-2007, 03:46 AM
Wow! Almost simultaneous replies! Thanks for the help.