0

add array element if get duplicate element in php

$a=[3.00,3.00,8.00,3.00,13.00]
$b=[0.11,0.45,0.22,0.90,0.44]

the result should be:

$c=[3.00,8.00,13.00]
$d=[1.46(0.11+0.45+0.90),0.22,0.44]
8
  • I'm a little confused on how you got $d. Commented Mar 10, 2018 at 7:17
  • What is 1.46 here? Something like weight of every number? Commented Mar 10, 2018 at 7:18
  • 1.46=.11+.45+.90 because in $a 3 values are same Commented Mar 10, 2018 at 7:20
  • Then why first element of $d is 1.46*1.46, the others just 0.22 & 0.44 not 0.22*0.22, 0.44*0.44? Commented Mar 10, 2018 at 7:22
  • a question that foul your mind. Commented Mar 10, 2018 at 7:26

3 Answers 3

2

Just as I don't like having the added isset logic, I create an array of the unique keys, then create a start array with 0 values for the sum values. Then just match the initial array against the unique array and add the value in...

$a=[3.00,3.00,8.00,3.00,13.00];
$b=[0.11,0.45,0.22,0.90,0.44];

$c = array_values(array_unique($a));
$d = array_fill(0, count($c), 0);
foreach ( $a as $key => $value )    {
    $d[ array_search($value, $c) ] += $b[$key];
}

print_r($c);
print_r($d);
Sign up to request clarification or add additional context in comments.

Comments

0

You can do that with a loop, like this:

$C,D; //That be inizialite like array
for ($i = 0; $i <= count($A); $i++)
    if (array_key_exists($A[$i], $C))
        $D[array_search($A[$i], $C)]+=$B[$i];
    else
        {array_push($C,$A[$i]);
         array_push($D,$B[$i]);
        }

I'm not sure that work, but the logic is that.

Comments

0
<?php
$a = [3.00, 3.00, 8.00, 3.00, 13.00];
$b = [0.11, 0.45, 0.22, 0.90, 0.44];
$c = array();
$d = array();

foreach ($a as $index => $per_a) {
    if (!in_array($per_a, $c)) {
        array_push($c, $per_a);
        array_push($d, $b[$index]);
    }
    else {
        $pos = array_search($b[$index], $d);
        $d[$pos] += $b[$index];
    }
}

print_r($c);
print_r($d);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.