...

View Full Version : Multiply arrays?



Sonjaaa
09-14-2009, 02:22 AM
Can you multiply arrays in PHP?

Like the array (1, 2, 3) multiplied by (10, 20) would create an array of all the possible results, i.e. an array of 6 items like (1*10, 1*20, 2*10, 2*20, 3*10, 3*20)?

Sonja

Sonjaaa
09-14-2009, 03:21 AM
Is there a way of doing it with array_walk?

Zangeel
09-14-2009, 05:06 AM
Assuming youre example is exactly what you want:



<?php
$aNumbers = range(1,20); #Create array of 1 through 20

print_r($aNumbers); #Show Array

for ($i = 0 ; $i < count($aNumbers) ; $i++)
{
$aMulti = (($i % 2) == 1) ? 10 : 20 ; #If odd, 20, if even 10
$aNumbers[$i] = $aNumbers[$i] * $aMulti; #Multiplay the array pieces
}

print_r($aNumbers); #New Array
?>

funnymoney
09-14-2009, 09:48 AM
or like this..


<?php
$array_multiplicand = array(1,2,3);
$array_multiplier = array(10,20);

$i=0;
while($i<count($array_multiplicand)) {
foreach ($array_multiplier as $multiplier) {
$array_product[] = $array_multiplicand[$i] * $multiplier;
}
$i++;
}
print_r($array_product);

//outputs Array ( [0] => 10 [1] => 20 [2] => 20 [3] => 40 [4] => 30 [5] => 60 )
?>



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum