0

I want to leave duplicates inside my array and only delete one occurrence when a value is found more than once.

Given an array of:

$array = ['+5', '+5', '+3', '+3', '+3', '+3', '+5', '+5'];

+5 and +3 each occur four times. I want to remove just one of the +5 values and just one of the +3 values, then find the sum of the remaining values.

$duplicate = ['+5', '+3'];
$array = ['+5', '+5', '+3', '+3', '+3', '+3', '+5', '+5'];

$i = 0;
foreach ($duplicate as $dup) {
    if (strpos($duplicate[$i], '+') !== false) {
        $duplicate[$i] = preg_replace('/[^0-9,:]/', '', $duplicate[$i]);
        $duplicate[$i] = "-$duplicate[$i]";
    }
    $i++;
}
$sum = array_merge($duplicate, $array);
$end_value = array_sum(array_values($sum));
var_export($end_value);

For my input, the final sum should be 24 (15 + 9).

6
  • I don't understand the cards count them self. Please reinforce the required logic by presenting your exact desired result based on your sample input. Do you expect this? 3v4l.org/24GRd Commented Sep 2, 2021 at 23:51
  • I see explode() being called, but I don't see $expode being used anywhere. Are we working from a hyphen-delimited string ($player_cards[$i2])? If so, I can potentially remove a duplicate without iterated function calls. Please explain further. Commented Sep 2, 2021 at 23:59
  • $player_cards was just a list of cards, explode() was not needed i didn't mean to add it in the code. thank you for your help but i did find a way to work around the problem by creating a $duplicate_array, and adding duplicates to the array. i then took there opposite values and add them to the main $add_p1_f1 array Commented Sep 3, 2021 at 0:33
  • There is often more than one way to solve a programming problem. It is important to future researchers that your question is super clear. Please added the requested details to your question and confirm whether my solution delivers your expected output. Commented Sep 3, 2021 at 0:43
  • No. You are not understanding Stack Overflow page design. Please take the tour. You are making a mess and not making a complete question as I've asked. You are ignoring my request to confirm my demo link provides the desired result. This is the new required output, right? 3v4l.org/M20nU Commented Sep 3, 2021 at 1:03

2 Answers 2

1

You need to remember what value you deleted from the array. In below script you save te value if it apperas at the first time, in $existsValues array. If you find the same value again you delete it (and save information that you did it in $deletedValues array). If value exists in both arrays then you just do nothing with it. In this way you delete always the second occurence of the value and nothing more.

$existsValues = [];
$deletedValues = [];
foreach ($add_array as $key => $value) {
    if (!in_array($value, $existsValues)) {
        $existsValues[] = $value;
    } else {
        if (!in_array($value, $deletedValues)) {
            $deletedValues[] = $value;
            unset($add_array[$key]);
        }
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

well what i did was add all duplicates into $duplicates_array, i then took them and flip there value so that (+5) was turn into (-5) and (+3) = (-3)... i then just used array_merge( $duplicate[] ,$add_p1_f1[] ) and array_sum(array_values($add_p1_f1[] ));
If the task ultimately ends with summing the card values, then array_values() is not needed. Resolving techniques must not be posted as comments. Resolving advice should be posted as an explained answer.
i have a working code i posted as the answer, thanks to mickmackusa for the Online PHP editor. you can take a look and see what i wanted to do ^^ anyways thanks for your answer and help!
0

The task of summing all values and omitting just one occurrence of all repeated values can be done without conditionally maintaining a duplicate array and definitely doesn't require regex.

Code: (Demo)

$array = ['+5', '+5', '+3', '+3', '+3', '+3', '+5', '+5'];

foreach (array_count_values($array) as $value => $count) {
    if ($count > 1) {
        unset($array[array_search($value, $array)]);
    }
}
var_export(array_sum($array));    // 24

The above groups values and counts their occurrences. Then it removes just one of the values when the values occurs more than once. Then sum the altered array.


Or you can boil it down to a mathematical process: (Demo)

$total = 0;
foreach (array_count_values($array) as $value => $count) {
    $total += $value * ($count - ($count > 1));
}
echo $total;
// 24

^ if the count is greater than 1, subtract 1 from the multiplier. (if $count > 1, then true is treated as 1; otherwise 0).

1 Comment

@Ulta I'll recommend that you use my second snippet in your project if you don't actually need to modify the input array.

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.