0

I have following array

Array (
    [0] => 1995,17500
    [1] => 2052,17500
    [2] => 2052,17500
    [3] => 2236,30000
    [4] => 2235,15000
    [5] => 2235,40000
);

I have exploded the value with comma ,.

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

      $newar = explode(',', $value);
}

So I have similar first value i.e $newar["0"]. For example 2235 and 2052. And I would like to have sum of second value i.e $newar["1"].

How can I achieve following result with PHP.

Array (
   [0] => 1995, 17500
   [1] => 2052, 35000
   [2] => 2036, 30000
   [3] => 2235, 55000
)

1 Answer 1

1

You can create a new array key/index based and use array_key_exists to check if the key already exists. If so sum the value, if not create the key. This is not the exact result you want, but it's neater.

$newar = []; //New Array

foreach($array as $value) {
     $explArr = explode(',', $value);

     if(array_key_exists($explArr[0], $newar)){ //Check if the key already exists
        $newar[$explArr[0]] += $explArr[1]; //Sum value to existing key
     } else {
        $newar[$explArr[0]] = $explArr[1]; //Create key
     }
}

Your result array will look like this:

Array (
   [1995] => 17500
   [2052] => 35000
   [2036] => 30000
   [2235] => 55000
)
Sign up to request clarification or add additional context in comments.

2 Comments

@Uchiha Because? Micro-optimizing?

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.