开发者

How do I remove duplicate numbers?

HTML

<form method="post">
    <input type="text" name="values" value="1,2,1,3,4,2,2,5" />
    <button type="submit">Submit</butt开发者_运维技巧on>
</form>

PHP

if(isset($_POST['values']))
{
    $values = $_POST['values']); //remove duplicate numbers

    echo $values;
}

Output

1,2,3,4,5

How would that work? First sort the numbers? And then run them through a loop?


Your intution is correct: You'd sort and then loop.

But PHP already has built-ins that do all the work for you. Like this:

array_unique(explode(',', $_POST['values']));

and if you need a string again, use implode:

implode(',', array_unique(explode(',', $_POST['values'])));
  • http://www.php.net/array_unique
  • http://www.php.net/explode
  • http://www.php.net/implode


What you want is array_unique. Explode $values with comma, to get the array, then call array_unique.

<?php

$values = explode(',', $_POST['values']);
var_dump(array_unique($values));


Follow Steps:

  • First explode string to array using , as separator.
  • Delete duplicate values using array_unique
  • implode back array into string

Example:

$values = "1,2,1,3,4,2,2,5";
echo implode( ',' , array_unique( explode( ',', $values) ) );

Demo


<?php
$values = '6,5,4,1,2,1,3,4,2,2,5';
$values = explode(',', $values);
$values = array_unique($values);
sort($values);
$values = implode(',', $values);
// $values = 1,2,3,4,5,6


$array=array_unique(explode(',',$_POST['values']));    
$values=implode(',',$array);


Change your code to:

if(isset($_POST['values']))
{
    $values = $_POST['values']); 
    //remove duplicate numbers
    $values = explode(',', $values);
    $values = array_unique($values);
    $values = implode(',', $values);

    echo $values;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜