0

i want to mutiply all the values in a foreach array by itself

here is an example of the array Array ( [0] => 2.4 [1] => 6 ) , all i want to do is mutiply 2.4*6

foreach($pp_events as $key=>$value)
{
#echo $value;
$pick=mysql_query("select * from pick where eventid='$value'");
$row=mysql_fetch_array($pick);
$sum*=$row['startPrice'];

}

2 Answers2

4

There's no need to implement this yourself. PHP has a built-in function for multiplying all the values in an array - array_product(). Use that instead:

$products = array();
foreach ($pp_events as $key => $value) {
    $pick = mysql_query("select * from pick where eventid='$value'");
    $row = mysql_fetch_array($pick);
    $products[] = $row['startPrice'];
}

echo array_product($products);

See also:

Community
  • 1
  • 1
Amal Murali
  • 75,622
  • 18
  • 128
  • 150
0

You need to initialize the variable to 1, then your loop should work.

$product = 1;
foreach ($pp_events as $key => $value) {
    $pick = mysql_query("select * from pick where eventid='$value'");
    $row = mysql_fetch_array($pick);
    $product *= $row['startPrice'];
}
echo $product;

You can also do a single query, instead of a separate query for each value:

$events = implode(',', array_map(function($x) { return "'$x'"; }, $pp_events));
$pick = mysql_query("select startPrice from pick where eventid IN ($events)");
$product = 1;
while ($row = mysql_fetch_assoc($pick)) {
    $product = $row['startPrice'];
}
echo $product;
Barmar
  • 741,623
  • 53
  • 500
  • 612