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

Asked

Viewed 160 times

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;
  • Tried something already?

  • $b = array("a" => 1+2, "b" => 2+3, "c" => 3+4); echo "sum(b) = ". array_sum($b)." n";

  • I’m having trouble separating the two

2 answers

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>";
}
  • Thank you. It helped a lot

1


I don’t know if it’s ideal, or if that question has dup, but a way that can make:

$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 )
 */
  • Thank you !! Helped me a lot

Browser other questions tagged

You are not signed in. Login or sign up in order to post.