w3resource

PHP Exercises: Print out the sum of pairs of numbers of a given sorted array of positive integers that is equal to a given number

PHP: Exercise-44 with Solution

Write a PHP program to print out the sum of pairs of numbers of a given sorted array of positive integers which is equal to a given number.

Sample Solution:

PHP Code:

<?php
// Define a function to find pairs in an array that sum up to a given value
function find_Pairs($nums, $pair_sum) {
    // Initialize an empty string to store pairs
    $nums_pairs = "";

    // Iterate through each element in the array
    for ($i = 0; $i < count($nums); $i++) {
        // Iterate through subsequent elements to find pairs
        for ($j = $i + 1; $j < count($nums); $j++) {
            // Check if the sum of the current pair equals the target sum
            if ($nums[$i] + $nums[$j] == (int)$pair_sum) {
                // Concatenate the pair to the result string
                $nums_pairs .= $nums[$i] . "," . $nums[$j] . ";";
            }
        }
    }

    // Return the string containing pairs
    return $nums_pairs;
}

// Test the function with example array and pair sums
$nums = array(0, 1, 2, 3, 4, 5, 6);
echo find_Pairs($nums, 7)."\n";
echo find_Pairs($nums, 5)."\n";

?>

Sample Output:

1,6;2,5;3,4;                                                
0,5;1,4;2,3; 

Flowchart:

Flowchart: Swap two variables

PHP Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a PHP program that multiplies corresponding elements of two given lists.
Next: Write a PHP program to compute the sum of the digits of a number.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.