i have an array {
$e = Array ( [0] => 13 [1] => 11 [2] => 2 ) Array ( [989.32] => 13 [77] => 11 [0.99] =>2 );
and i want to multiply each key by their values respectively and use the values to create another array. Anyone know how? i've tried:
foreach($e as $y=>$z)
{$x= $y * $z;
$p=array();
array_push($p,$x);}
print_r($p);
but i got:
Array ( [0] => 1.98 )
One little change in your code:
$p=array();
foreach($e as $y=>$z)
{
$x= $y * $z;
array_push($p,$x);
}
print_r($p);
Try this :
$p=array();
foreach($e as $y=>$z){
$x= $y * $z;
array_push($p,$x);
}
print_r($p);
Put your $p=array();
out side the loop
I assume your array was multidimensional array. so try like this
$e = Array(Array ( "0" => 13 , "1" => 11 , "2" => 2 ), Array ( "989.32" => 13 , "77" => 11 , "0.99" => 2 ));
$result = array();
$i=0;
foreach($e as $values)
{
foreach($values as $key=>$value)
{
$result[$i]= $key * $value ;
$i++;
}
}
print_r($result);
Hope you will understand why:
<?php
$e = array(...);
$p = array();
foreach ($e as $y => $z) {
$x = $y * $z;
array_push($p, $x);
}
So as you can see, in your code, you overwrite $p each time so that you get the last multiplication 0.99 * 2 = 1.98