Replace repeating value with zero in PHP string

The following is the code

<?php
$id ="202883-202882-202884-0";
$str = implode('-',array_unique(explode('-', $id)));
echo $str;
?>

The result is

202883-202882-202884-0

for $id ="202883-202882-202882-0";, result is 202883-202882-0

I would like to replace the duplicate value with zero, so that the result should be like 202883-202882-0-0, not just remove it.

and for $id ="202883-0-0-0";, result should be 202883-0-0-0. zero should not be replaced, repeating zeros are allowed. How can I archive that?

More info:
I want to replace every duplicate numbers. Because this is for a product comparison website. There will be only maximum 4 numbers. each will be either a 6 digit number or single digit zero. all zero means no product was selected. one 6 digit number and 3 zero means, one product selected and 3 blank.

Each 6 digit number will collect data from database, I dont want to allow users to enter same number multiple times (will happen only if the number is add with the URL manually.).

Update: I understand that my question was not clear, may be my English is poor. Here is more explanation, this function is for a smartphone comparison website. The URL format is sitename.com/compare.html?id=202883-202882-202889-202888. All three numbers are different smartphones(their database product ID). I dont want to let users to type in the same product ID like id=202883-202882-202882-202888. It will not display two 202882 results in the website, but it will cause some small issues. The URL will be same without change, but the internal PHP code should consider it as id=202883-202882-202888-0. The duplicates should be replaced as zero and added to the end. There will be only 4 numbers separated by "-". The following examples might clear the cloud!

if pid=202883-202882-202889-202888 the result should be 202883-202882-202889-202888 if pid=202883-202883-202883-202888 the result should be 202888-0-0-0 if pid=202883-202882-202883-202888 the result should be 202883-202882-202888-0 if pid=202882-202882-202882-202882 the result should be 202882-0-0-0

I want to allow only either 6 digit numbers or single digit zero through the string.

if pid=rgfsdg-fgsdfr4354-202883-0 the result should be 202883-0-0-0 if pid=fasdfasd-asdfads-adsfds-dasfad the result should be 0-0-0-0 if pid=4354-45882-445202882-202882 the result should be 202882-0-0-0

It is too complicated for me create, I know there are bright minds out there who can do it much more efficiently than I can.

Answer

Solution:

You can do a array_unique (preserves key), then fill the gaps with 0. Sort by key and you are done :)

+ on arrays will the arrays but prioritizes the one on the left.

Code

$input = "0-1-1-3-1-1-3-5-0";
$array = explode('-', $input);
$result = array_unique($array) + array_fill(0, count($array), 0);
ksort($result);

var_dump(implode('-',$result));

Code (v2 - suggested by mickmackusa) - shorter and easier to understand

Fill an array of the size of the input array. And replace by leftover values from array_unique. No ksort needed. 0s will be replaced at the preserved keys of array_unique.

$input = "0-1-1-3-1-1-3-5-0";
$array = explode('-', $input);
$result = array_replace(array_fill(0, count($array), 0), array_unique($array));
var_export($result);

Working example.

Output

string(17) "0-1-0-3-0-0-0-5-0"

Working example.

references

  • ksort - sort by key
  • array_fill - generate an array filled with 0 of a certain length

Answer

Solution:

This is another way to do it.

$id = "202883-202882-202882-0-234567-2-2-45435";

From the String you explode the string into an array based on the delimiter which in this case is '-'/

$id_array = explode('-', $id);

Then we can loop through the array and for every unique entry we find, we can store it in another array. Thus we are building an array as we search through the array.

$id_array_temp = [];
// Loop through the array
foreach ($id_array as $value) {
    if ( in_array($value, $id_array_temp)) {
        // If the entry exists, replace it with a 0
        $id_array_temp[] = 0;
    } else {
        // If the entry does not exist, save the value so we can inspect it on the next loop.
        $id_array_temp[] = $value;
    }
}

At the end of this operation we will have an array of unique values with any duplicates replaced with a 0.

To recreate the string, we can use implode...

$str = implode('-', $id_array_temp);
echo $str;

Refactoring this, using a ternary to replace the If,else...

$id_array = explode('-', $id);
$id_array_temp = [];
foreach ($id_array as $value) {
    $id_array_temp[] = in_array($value, $id_array_temp) ? 0 : $value;
}
$str = implode('-', $id_array_temp);
echo $str;

Output is

202883-202882-0-0-234567-2-0-45435

Answer

Solution:

This appears to be a classic XY Problem.

The essential actions only need to be:

  1. Separate the substrings in the hyphen delimited string.
  2. Validate that the characters in each substring are in the correct format AND are unique to the set.
  3. Only take meaningful action on qualifying value.

You see, there is no benefit to replacing/sanitizing anything when you only really need to validate the input data. Adding zeros to your input just creates more work later.

In short, you should use a direct approach similar to this flow:

if (!empty($_GET['id'])) {
    $ids = array_unique(explode('-', $_GET['id']));
    foreach ($ids as $id) {
        if (ctype_digit($id) && strlen($id) === 6) {
        // or: if (preg_match('~^\d{6}$~', $id)) {
            takeYourNecessaryAction($id);
        }
    }
}

Source