Skip to content
Advertisement

How to calculate two data in one array?

I’m a beginner in php, I want to calculate two data from one array, but I still don’t understand how. For example, I have one data array

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

and I want the output like this

1x2 = 2
1x3 = 3
1x4 = 4
2x3 = 6
2x4 = 8
3x4 = 12

I try some code but didn’t help, and now I got stuck.

sorry my language is not good.

Advertisement

Answer

Just use two loops to iterate over the data:

<?php
$input = [1, 2, 3, 4];
foreach ($input as $left) {
  foreach ($input as $right) {
    if ($left < $right) {
      echo sprintf("%dx%d = %dn", $left, $right, $left*$right);
    }
  }
}

For bigger data sets you might want to optimize it. Faster but harder to read:

<?php
$input = [1, 2, 3, 4];
foreach ($input as $key => $left) {
  foreach (array_slice($input, $key+1) as $right) {
    echo sprintf("%dx%d = %dn", $left, $right, $left*$right);
  }
}

The output obviously is:

1x2 = 2
1x3 = 3
1x4 = 4
2x3 = 6
2x4 = 8
3x4 = 12
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement