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 ); ?> |
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.