humphrey humphrey - 11 days ago 7
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
$(document).ready(function(){
$("ul li").click(function(event) {
var eid = $(this).attr('id');
$(".text").val($(".text").val() +"\n" + eid);

});
});
//parents_idcelldrag
</script>


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

<?php
// 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

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);