function run_tests() { $jsons = ['[1,2,3]', '{"a":2,"b":4, "c":"lol"}', '[[[3]]]', '{"a":{"b":4},"c":-1}', '{"a":[-1,1]}', '[-1,{"a":1}]', '[]', '{}']; $sums = [6, 6, 3, 3, 0, 0, 0, 0]; foreach ($jsons as $index => $json) { var_dump(sum_numbers(json_decode($json)) === $sums[$index]); } $jsons = ['[1,2,3]', '[1,{"c":"red","b":2},3]', '{"root": {"d":"red","e":[1,2,3,4],"f":5}}', '[1,"red",5]']; $sums = [6, 4, 0, 6]; foreach ($jsons as $index => $json) { var_dump(sum_numbers(json_decode($json), true) === $sums[$index]); } }
// print out a multiplication table up to 12 echo '<table><tr>'; for ($row = 1; $row <= 12; ++$row) { if ($row != 1) { echo '</tr><tr>'; } for ($col = 1; $col <= 12; ++$col) { echo '<td>' . $row * $col . '</td>'; } } echo '</tr></table>'; echo '***********<br /><br />'; // sum the numbers between two numbers function sum_numbers($num1, $num2) { $summed = 0; if ($num1 < $num2) { for ($i = $num1 + 1; $i < $num2; ++$i) { $summed += $i; } } else { for ($i = $num2 + 1; $i < $num1; ++$i) { $summed += $i; } } return $summed; } $x = 5; $y = 8; echo 'The sum of ' . $x . ' and ' . $y . ' is ' . sum_numbers($x, $y) . '.';
<!--Problem 2. Sum Two Numbers Write a PHP script SumTwoNumbers.php that decleares two variables, firstNumber and secondNumber. They should hold integer or floating-point numbers (hard-coded values). Print their sum in the output in the format shown in the examples below. The numbers should be rounded to the second number after the decimal point. Find in Internet how to round a given number in PHP. --> <?php function sum_numbers($first_number, $second_number) { return $first_number . " + " . $second_number . " = " . ($first_number + $second_number) . "\n"; } echo sum_numbers(2, 5); echo sum_numbers(1.567808, 0.356); echo sum_numbers(1234.5678, 333);