humphrey humphrey - 1 year ago 87
PHP Question

How can I ignore duplicates from an array

I want my program to ignore duplicates ,
I have used array_unique but I still see duplicates
I wonder what am doing wrong .
So I get the phone numbers from the text area then I send them into my php
Any help will be appreciated
here is what I have tried .

<script type="text/javascript">
// click and drop code
$("ul li").click(function(event) {
var eid = $(this).attr('id');
$(".text").val($(".text").val() +"\n" + eid);


<form action="index.php" method="post">
<textarea class="text" name = "cellnumbers" readonly></textarea>

// I get this
$cellnumbers=(isset($_POST['cellnumbers']))? trim($_POST['cellnumbers']): '';

$ids = explode("\n", $cellnumbers);
$cleaned = array_unique($ids);
foreach($cleaned as $key){
$final_cell .= $key.',';

$final_cell= substr($final_cell,0,-1);
echo $final_cell;

Answer Source

It can be the case if $ids have trailing whitespace. Try to trim values before do array_unique:

$ids = explode("\n", $cellnumbers);
$ids = array_map('trim', $ids);
$cleaned = array_unique($ids);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download