-1

I have 2 arrays in PHP7:

$Array1 = ["bus","bus","int"];
$Array2 = [2,18,10];

Where $Array1 is key and $Array2 is value for each index.
I need to combine both and sum values for duplicate keys, e.g. get following output:

$Array3 = ["bus" => 20, "int" => 10];

Thank you!

Aleksey
  • 61
  • 6
  • If there are no duplicate keys then you can use [`array_combine()`](http://php.net/manual/en/function.array-combine.php). If there are duplicate keys then [`array_map()`](http://php.net/manual/en/function.array-map.php) is a possible solution. In both situations, a plain `foreach` loop can do the job as well. Have you tried something? – axiac Oct 10 '17 at 16:18

3 Answers3

2

The code you need is as easy as that:

// The input arrays
$Array1 = ['bus', 'bus', 'int'];
$Array2 = [2, 18, 10];

// Build the result here
$Array3 = [];

// There is no validation, the code assumes that $Array2 contains
// the same number of items as $Array1 or more
foreach ($Array1 as $index => $key) {
    // If the key $key was not encountered yet then add it to the result
    if (! array_key_exists($key, $Array3)) {
        $Array3[$key] = 0;
    }

    // Add the value associate with $key to the sum in the results array
    $Array3[$key] += $Array2[$index];
}

print_r($Array3);

Its output:

Array
(
    [bus] => 20
    [int] => 10
)
axiac
  • 68,258
  • 9
  • 99
  • 134
0

This one could work:

$Array1 = ['bus', 'bus', 'int'];
$Array2 = [2, 18, 10];

# Let $Array3 be the required results array.
 $Array3 = [];
 for($j = 0; $j < count($Array1); $j += 1){
  $k = $Array1[$j];
  /*If the key already exists in $Array3 , add to it the value in the present key, 
   else just enter it as a new element. */
 if(array_key_exists($k,$Array3)){ $Array3[$k] = $Array3[$k] + $Array2[$j];}
   else { 
# But first check that the length of $Array2 is not exceeded
   if($j <= count($Array2)){
    $Array3[$k] = $Array2[$j];
          }
       }
 }

 print_r($Array3);

        # gives: Array ( [bus] => 20 [int] => 10 ) 
  • Hi John, thank you very much for the prompt answer! In my case, both Array1 and Array2 has same length by default, so i went with code from @axiac, but you solution works perfectly. Specifically when length validation is needed. thank you very much indeed. – Aleksey Oct 10 '17 at 20:04
-1

i will make it. i hope it will helpful for you: you can get your required out put by using an extra array, first of all, count your array elements, this will you condition. this simple check

$Array1[$x] == $Array1[$x+1]

will check if the array consecutive address have same value. (the condition is array must be sorted),

and the other value like this:

 $arr[$Array1[$x]] // assign a key

this is for making it associate array :

$Array1 = ["bus","bus","int"];
$Array2 = [2,18,10];

$arr = [];

for ($x = 0; $x < count($Array1); $x++) {
  if($Array1[$x] == $Array1[$x+1])
    {
      $arr[$Array1[$x]] = $Array2[$x] + $Array2[$x+1]; 
      $x++;
    }
  else
    {
     $arr[$Array1[$x]] = $Array2[$x];
    }

}

the output is:

Array ( [bus] => 20 [int] => 10 )
Ahmad Hassan
  • 371
  • 4
  • 22
  • Thank you for this code snippet, which may provide some immediate help. A proper explanation [would greatly improve](https://meta.stackexchange.com/q/114762) its educational value by showing why this is a good solution to the problem, and would make it more useful to future readers with similar, but not identical, questions. Please edit your answer to add explanation, and give an indication of what limitations and assumptions apply. – GrumpyCrouton Oct 10 '17 at 16:27
  • This code only works if the identical keys are next to each other. Also `$Array1[$x+1]` is not a valid index in the last iteration of the loop. – SirDarius Oct 10 '17 at 16:29
  • array must be sorted – Ahmad Hassan Oct 10 '17 at 16:33
  • OP does not list sorted arrays as a requirement. This would imply you'd need to sort the values array at the same time, which is impractical given that it is as much work as using an algorithm that would work for unsorted arrays. – SirDarius Oct 10 '17 at 16:36
  • Change the first array to `['bus', 'int', 'bus']` and this piece of code produces incorrect and confusing results. – axiac Oct 10 '17 at 16:49
  • Thank you Ahmad! You solution also works perfectly. In my case both Key and Value arrays have both length, so I dropped length check. But perfect solution as with the other 2. Thank you. – Aleksey Oct 10 '17 at 20:07
  • Welcome bro! so finally i got a person which respect the person who tried instead leg pulling. – Ahmad Hassan Oct 10 '17 at 20:50
  • Comments are meant to help the poster to improve their answer. There is no lack of respect intended by anyone in this thread. As it stands, and despite what OP says, the code you posted has bugs, which could be solved easily. (And on a personal standpoint, I've been given way much harsher comments in the past for admitted errors in my answers). – SirDarius Oct 11 '17 at 08:29