PHP algorithm 1,2,3,4 = 1 + 2, 2 + 3, 3 + 4

1

For example, I have this array:

$Ids = array(1, 2, 3, 4);

Below is the result I would like to get:

$Pair [0] = 1 + 2;
$Pair [1] = 2 + 3;
$Pair [2] = 3 + 4;
    
asked by anonymous 22.05.2017 / 01:32

2 answers

1

I do not know if it's the ideal, or if that question has dup, but a way it can do:

$Ids = array(1, 2, 3, 4);
for($i = 1; $i < count($Ids); $i++)
{
    echo $Ids[($i-1)]." + ".$Ids[($i)]."<br/>";
}

/* Imprime:
 * 1 + 2
 * 2 + 3
 * 3 + 4
 */

If you want to play the sum in a new array:

$Ids = array(1, 2, 3, 4);
$newArray = array();
for($i = 1; $i < count($Ids); $i++)
{
    $newArray[] = $Ids[($i-1)] + $Ids[($i)];
}

print_r($newArray);
/* Imprime:
 * Array ( [0] => 3 [1] => 5 [2] => 7 )
 */
    
22.05.2017 / 01:45
3

example - ideone

$Ids = array(1, 2, 3, 4);
$result = count($Ids);

for ($i = 0; $i < ($result-1) ; $i++) {
   echo "\$Pair [".$i."] = ".$Ids[$i]. "+" .$Ids[$i+1];
   echo "<br>";
}
    
22.05.2017 / 01:45