How to do this without having to make two loops.
Example method:
function getPairNumbers($array, $valor) {
//aqui viria o método
}
How to do this without having to make two loops.
Example method:
function getPairNumbers($array, $valor) {
//aqui viria o método
}
You can test each position, at the beginning and at the end of the array, and then test each position and increment as you find the desired value:
<?php
function getPairNumbers($numbers, $target)
{
$result = array();
sort($numbers);
$high = count($numbers) - 1;
for ($i = 0; $i < count($numbers);) {
if ($numbers[$i] + $numbers[$high] == $target) {
$result[0] = $numbers[$i];
$result[1] = $numbers[$high];
break;
}
if ($numbers[$i] + $numbers[$high] < $target) {
$i++;
}
if ($numbers[$i] + $numbers[$high] > $target) {
$high--;
}
if ($high <= $i) {
return null;
}
}
return $result;
}
$arr = getPairNumbers(array(1,4,5,15,30,25,20,0,13), 18);
print_r($arr);