array_unique not giving expected result

125 views Asked by At

I'm trying to grab all the unique values of an array.

$Arr_TitleID = "92 1 92 38 1 6 1";
echo "Arr_TitleID: " . $Arr_TitleID;

$TitleID_Explode = explode(" ", $Arr_TitleID);
$BigTitleID_Explode = array_unique($TitleID_Explode);

$CTID_count = count($BigTitleID_Explode);
echo "count(CTID_count): " . $CTID_count;

for($i = 0; $i < $CTID_count; $i++)
{
    echo "Piece $i = $BigTitleID_Explode[$i]";
}

Output:

Arr_TitleID: 92 1 92 38 1 6 1
count(CTID_count): 4
Piece 0 = 92
Piece 1 = 1
Piece 2 = 
Piece 3 = 38

Where is number 6? And why is there a blank where the number 6 should be?

3

There are 3 answers

0
MD SHAHIDUL ISLAM On

array index is not sequential like 0, 1, 2, 3

array index is 0, 1, 3, 5

Array
(
    [0] => 92
    [1] => 1
    [3] => 38
    [5] => 6
)

So edit code like this, just add one line to re-indexing as numeric value

$Arr_TitleID = "92 1 92 38 1 6 1";
echo "Arr_TitleID: " . $Arr_TitleID;

$TitleID_Explode = explode(" ", $Arr_TitleID);
$BigTitleID_Explode = array_unique($TitleID_Explode);

//just add bellow line

$BigTitleID_Explode = array_values($BigTitleID_Explode);

//

$CTID_count = count($BigTitleID_Explode);
echo "count(CTID_count): " . $CTID_count;

for($i = 0; $i < $CTID_count; $i++)
{
    echo "Piece $i = $BigTitleID_Explode[$i]";
}
1
Nikhil Mohan On

The output of your script seems like this,

Array
(
    [0] => 92
    [1] => 1
    [3] => 38
    [5] => 6
)

To iterate using for loop, you should use array_values or try foreach loop instead of for.

Using array_values you will get a numeric indexed array,

$BigTitleID_Explode = array_values(array_unique($TitleID_Explode));

Result should be,

Array
    (
        [0] => 92
        [1] => 1
        [2] => 38
        [3] => 6
    )
0
Gary Hayes On

Here is your problem. While you may be finding the unique values, the array is not creating new keys, so your counter isn't going high enough to catch the last key.

$Arr_TitleID = "92 1 92 38 1 6 1";
echo "Arr_TitleID: " . $Arr_TitleID;
$TitleID_Explode = explode(" ", $Arr_TitleID);
$BigTitleID_Explode = array_unique($TitleID_Explode);
print_r($BigTitleID_Explode);
$CTID_count = count($BigTitleID_Explode);
echo "count(CTID_count): " . $CTID_count;
for($i = 0; $i < $CTID_count; $i++)
{
    echo "Piece $i = $BigTitleID_Explode[$i]";
}

The print_r line I added outputs this: Array ( [0] => 92 1 => 1 [3] => 38 [5] => 6 )

Value 6 is on key 5.

I suggest using a sort function in the place where my added line is, then everything will work out fine.

There are many to choose from, so I cannot suggest one as I don't know which one you'll need for your purposes, but here is a list with references.

http://www.w3schools.com/php/php_ref_array.asp