How to Find Matching Pair from an Array in PHP ?
Last Updated :
02 Jan, 2024
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.
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.
Example:
PHP
<?php
function pairSum( $arr , $targetSum ) {
$pairs = [];
$len = count ( $arr );
for ( $i = 0; $i < $len - 1; $i ++) {
for ( $j = $i + 1; $j < $len ; $j ++) {
if ( $arr [ $i ] + $arr [ $j ] == $targetSum ) {
$pairs [] = [ $arr [ $i ], $arr [ $j ]];
}
}
}
return $pairs ;
}
$arr = [2, 7, 4, 5, 11, 15];
$sum = 9;
$result = pairSum( $arr , $sum );
print_r( $result );
?>
|
Output
Array
(
[0] => Array
(
[0] => 2
[1] => 7
)
[1] => Array
(
[0] => 4
[1] => 5
)
)
Finding Duplicate Pairs
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.
Example:
PHP
<?php
function duplicatePairs( $arr ) {
$pairs = [];
$len = count ( $arr );
for ( $i = 0; $i < $len - 1; $i ++) {
for ( $j = $i + 1; $j < $len ; $j ++) {
if ( $arr [ $i ] == $arr [ $j ]) {
$pairs [] = [ $arr [ $i ], $arr [ $j ]];
}
}
}
return $pairs ;
}
$arr = [1, 2, 3, 2, 4, 1];
$res = duplicatePairs( $arr );
print_r( $res );
?>
|
Output
Array
(
[0] => Array
(
[0] => 1
[1] => 1
)
[1] => Array
(
[0] => 2
[1] => 2
)
)
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 ;
}
$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
(
...
Share your thoughts in the comments
Please Login to comment...