I came across this php interview question while researching pre-interview test questions.
Given an array of integers, compute a total score based on the following rules:
- Add 1 point for every even number in the array
- Add 3 points for every odd number in the array
- Add 5 points for every time you encounter an 8 in the array
Examples:
Input:
my_numbers = [1, 2, 3, 4, 5]
Output: 11
Input:
my_numbers=[15, 25, 35]
Output:
9
Input:
my_numbers=[8, 8]
Output:
10
How to approach this particular task? my attempt
<?php function find_total( $my_numbers ) {
//Insert your code here \
$total = 0;
foreach($my_numbers as $val) {
if ($val % 2 == 0) {
echo (++$val);
} else
echo ($val += 3);
}
if ($val == 8) {
echo($val += 5);}
}
?>