Randel Ramirez
Randel Ramirez

Reputation: 3761

How to check for duplicates in an array and then do something with their values in PHP?

I have an array for example ("1:2","5:90","7:12",1:70,"29:60") Wherein ID and Qty are separated by a ':' (colon), what I want to do is when there's a duplicate of IDs the program will add the qty and return the new set of arrays so in the example it will become ("1:72","5:90","7:12","29:60").

Ex.2

("1:2","5:90","7:12","1:70","29:60","1:5") 

becomes

("1:77","5:90","7:12","29:60").

Upvotes: 0

Views: 82

Answers (4)

Roman Newaza
Roman Newaza

Reputation: 11700

<?php

$arr = array("1:2","5:90","7:12", "1:70","29:60");

$newArr = array();

foreach($arr as $key => $value) {

  list($id, $quantity) = explode(':', $value);

  if(isset($newArr[$id]))
    $newArr[$id] += $quantity;
  else
    $newArr[$id] = $quantity;

}

foreach($newArr as $key => $value) {
  $newArr[$key] = "$key:$value";
}

print_r($newArr);

Upvotes: 1

Lake
Lake

Reputation: 913

Try to do like this

$array  = array("1:2","5:90","7:12","1:70","29:60","1:5");
$result = array();
$sum    = array();
foreach($array as $value)
{
        list($k,$v) = explode(':',$value);
        $sum[$k]   += $v; 
        $result[$k] = $k.':'.$sum[$k];
}
unset($sum);
print_r($result); 

Upvotes: 1

deceze
deceze

Reputation: 522626

Assuming the data format is an actual array, or you can parse it into one:

$data = array("1:2","5:90","7:12","1:70","29:60","1:5");
$values = array();
foreach ($data as $value) {
    list($id, $qty) = explode(':', $value);
    if (isset($values[$id])) {
        $values[$id] += $qty;
    } else {
        $values[$id] = $qty;
    }
}
foreach ($values as $id => &$qty) {
    $qty = "$id:$qty";
}
$values = array_values($values);

Upvotes: 1

Cheery
Cheery

Reputation: 16214

Simple step by step:

  $arr = array("1:2","5:90","7:12","1:70","29:60");
  $tmp = array();
  foreach($arr as $item)
  {
   list($id, $value) = explode(':', $item);
   if (isset($tmp[$id])) 
        $tmp[$id] += $value;
   else
        $tmp[$id] = $value;
  }

  $arr = array();
  foreach($tmp as $id => $value)
    array_push($arr, $id . ':' . $value);

  var_dump($arr);

Upvotes: 1

Related Questions