0

I have a really simple question but for some reason the output is not what I want. I have 2 arrays:

total_hours = array(10, 20, 30);
hourly_rate = array(15, 10, 15);

So what I want to work out is how to multiple the corresponding element of total_hours with the hourly_rate (e.g. element 1: 10*15 = 150) then put this into an array called total_sum (total_sum has been initialized) . This is what I've done so far:

$total_sum = 0;
for($i=0; $i < sizeof($hourly_rate); $i++) {
    for($a=0; $a < sizeof($total_hours); $a++) {
        $total_sum = ($hourly_rate[$i]*$total_hours[$a]); 
    } 
    $total_pay[] = $total_sum;    
}  

At the moment I get 0 and don't understand why.

Many thanks!

2
  • Please clarify your question. Your code says total sum is an integer not an array. Also, what's this about 0? Your result seems to be an array. Commented Mar 10, 2013 at 17:33
  • My apologies, ignore the total sum. Also I get 0 when I do a print statement. Commented Mar 10, 2013 at 17:46

4 Answers 4

1

You can use array_map with anonymous function to multiply hours with rates. array_map iterates over given arrays and returns result as array. Look http://php.net/manual/en/function.array-map.php for more info.

$total_hours = array(10, 20, 30);
$hourly_rate = array(15, 10, 15);    

$total_pay = array_map(function($hour, $rate) {
    return $hour * $rate;
}, $total_hours, $hourly_rate);
Sign up to request clarification or add additional context in comments.

Comments

0

The following is based on this answer by Aarolama Bluenk, and should work as long as both arrays are the same size:

for($i = 0; $i < count($total_hours); $i++) {
    $result[] = $total_hours[$i] * $hourly_rate[$i];
}

Comments

0

You don't want to have two loops, just one:

$total_pay = array();
for($i=0; $i < count($hourly_rate); $i++) {
  $total_pay[] = $hourly_rate[$i]*$total_hours[$i]; 
}

To get the sum of your final array, use array_sum.

2 Comments

I've tried your suggestion but now for some reason it iterates 3 times and I have no idea why, don't suppose you have any idea?
It iterates three times because your array only has three elements in it. You wanted to multiply two arrays (each with three elements) together, so you only want to loop three times to make that happen.
0
$total_hours = array(10, 20, 30);
$hourly_rate = array(15, 10, 15);

$mi = new MultipleIterator();
$mi->attachIterator(new ArrayIterator($total_hours));
$mi->attachIterator(new ArrayIterator($hourly_rate));

$total_pay = array();
foreach($mi as $details) {
    $total_pay[] = $details[0] * $details[1];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.