Imran Omer Imran Omer - 1 month ago 8
PHP Question

Remove Duplicated Entries From an Array

For removing the duplicated entries I know I have to use

array_unique()
but unfortunately by using this I got unexpected result(s). My PHP code is this:

$query = $db->query("
SELECT sid,father_contact,residential_contact
FROM ".TABLE_PREFIX."student_list
{$where_clause}
ORDER BY sid ASC");
while ($s = $db->fetch_array($query))
{
if (!empty($s['father_contact']))
{
$father_contact = $s['father_contact'].', ';
}
else
{
$father_contact = '';
}

if (!empty($s['residential_contact']))
{
$residential_contact = $s['residential_contact'].', ';
}
else
{
$residential_contact = '';
}

$phone_nums_bit .= $father_contact.$residential_contact;
}


This grabs all phone numbers from the database tables and print the result like this:

03334523675, 03124237009, 03134237002, 03124237009, 03217832173, 03134237002, 3134237002, 03124237009,


Notice that few numbers like
03134237002
is repeating thrice. I want to remove duplicate entries from this result. Please help me to sort it out. Thanks.

Answer

You can try to do it via array structures. Just to give you an idea:

$phones = [];
while ($s = $db->fetch_array($query))
{
    if (!empty($s['father_contact']))
    {
        $phones[] = $s['father_contact'];
    }

    if (!empty($s['residential_contact']))
    {
        $phones[] = $s['residential_contact'];
    }
}
$phones = array_unique($phones);
// and then combine into string
$phone_nums_bit = implode(', ', $phones);