Finding Pairs with a Specific Value

To find pairs with a specific value, you can iterate through the array and check for elements that match the desired value.

Example:

PHP




<?php
  
function pairsWithValue($arr, $targetValue) {
    $pairs = [];
  
    foreach ($arr as $value) {
        if (in_array($targetValue - $value, $arr)) {
            $pairs[] = [$value, $targetValue - $value];
        }
    }
  
    return $pairs;
}
  
// Driver code
$arr = [3, 1, 4, 6, 5, 2];
$targetVal = 7;
  
$res = pairsWithValue($arr, $targetVal);
  
print_r($res);
  
?>


Output

Array
(
    [0] => Array
        (
            [0] => 3
            [1] => 4
        )

    [1] => Array
        (
            [0] => 1
            [1] => 6
        )

    [2] => Array
        (
     ...


How to Find Matching Pair from an Array in PHP ?

Given an Array, the task is to find the matching pair from a given array in PHP. Matching a pair from an array involves searching for two elements that satisfy a certain condition, such as having the same value, summing up to a specific target, or meeting some other criteria. Here, we will cover three common scenarios for finding matching pairs in an array.

Similar Reads

Finding Pairs with a Specific Sum

To find pairs in an array that add to a specific sum, you can use a nested loop to iterate through the array and check for pairs....

Finding Duplicate Pairs

...

Finding Pairs with a Specific Value

To find the duplicate pairs (pairs with the same values), you can use nested loops to compare each element with every other element in the array....