Skip to content
Advertisement

PHP subtract value of array from 2 arrays [closed]

result1 and result 2 are arrays, with arrays inside. i want to subtract the number of a given aaray, if the name is the same

for example Math 2 – Math 1 = Math 1

i kno i have to use foreach, but not much more

  $result1 = ['name' => 'Math', 'number'=> '2'],
             ['name' => 'Eng', 'number'=> '2'];
  $result2 = ['name' => 'Math', 'number' => '1'],
             ['name' => 'Eng', 'number' => '0'];

someone any ideas

Advertisement

Answer

I’ll try to answer basing on assumptions:

  • there are only 2 $result variables, not for example 3 or dynamic number of them.
  • each of them can have dynamic number of different subjects, in different orders, but if there is a subject in result2 it also has to exist in result1. Of course if results are always the same – only numbers are different it can be easier.
  • you want foreach.
  • you want to calculate all numbers at once.
$result1 = [['name' => 'Math', 'number'=> '2'], ['name' => 'Eng', 'number'=> '2']];
$result2 = [['name' => 'Math', 'number'=> '1'], ['name' => 'Eng', 'number'=> '0']];

$result3 = $result1;
foreach($result1 as $k => $r1) {
  foreach($result2 as $r2) {
    if ($r1['name'] === $r2['name']) {
      $result3[$k]['number'] = (string) ($result3[$k]['number'] - $r2['number']);
    }
  }
}

var_dump($result3);

And the result is:

array(2) {
  [0]=>
  array(2) {
    ["name"]=>
    string(4) "Math"
    ["number"]=>
    string(1) "1"
  }
  [1]=>
  array(2) {
    ["name"]=>
    string(3) "Eng"
    ["number"]=>
    string(1) "2"
  }
}

So Math is 1 (2-1), and Eng is 2 (2-0).

If “number” was an int it would be a bit simpler but you used string type for it.

Also if $results were keyed by subjects so:

$result1 = ['Math' => 2, 'Eng' => 2];

It would be as trivial as just doing $result1['Math'] - $result2['Math'] so you can consider transforming both $result variables to this format with this code:

$result1 = [['name' => 'Math', 'number'=> '2'], ['name' => 'Eng', 'number'=> '2']];

$result3 = [];
foreach ($result1 as $r1) {
  $result3[$r1['name']] = (int)$r1['number'];
}

var_dump($result3);

result:

array(2) {
  ["Math"]=>
  int(2)
  ["Eng"]=>
  int(2)
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement