settingsAccountsettings
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy
Menusettings

Q: Sum Adjacent Equal Numbers - PHP Array Task

+4 votes

Write a program to sum all adjacent equal numbers in a array of float numbers, starting from left to right:

sum adjacent equal numbers php array task

asked in PHP category by user andrew

3 Answers

+3 votes

Here is my solution:

<?php

$arr = array_map("floatval", explode(" ", readline()));

for ($i = 0; $i < count($arr) - 1; $i++) {

    if ($arr[$i] == $arr[$i + 1]) {
        $newElement = $arr[$i] + ($arr[$i + 1]);
        array_splice($arr, $i, 2, $newElement);
        $i -= 2;
    }
}
echo implode(" ", $arr);

 

answered by user samfred5830
+2 votes

My solution:

<?php

$input = array_map('floatval', explode(' ', readline()));
for ($i = 0; $i < count($input) - 1; $i++) {
    if ($input[$i] === $input[$i + 1]) {
        $element = $input[$i + 1] + $input[$i + 1];
        $input[$i] = $element;
        array_splice($input, $i + 1, 1);
        $i = -1;
    }
}
echo implode(' ', $input);
answered by user eiorgert
+1 vote

See more HERE about the additional functionality of the array() function in PHP/

answered by user mitko
...