Page 1 of 1

array_unique producing unexpected results... any help?

Posted: Tue Mar 18, 2008 7:49 pm
by masterkrang
I have an array called $image_arr that holds image names (strings).

print_r($image_arr); //produces the following result
Array ( [0] => 03578975.jpg [1] => 03578975.jpg [2] => 03578975c.jpg [3] => 03578975c.jpg [4] => 03578975b.jpg [5] => 03578975b.jpg [6] => 03578975e.jpg [7] => 03578975e.jpg [8] => 03578975f.jpg [9] => 03578975f.jpg [10] => 03578975a.jpg [11] => 03578975a.jpg [12] => 03578975d.jpg [13] => 03578975d.jpg [14] => 03578975g.jpg [15] => 03578975g.jpg )

Then after:

$uniq_image_arr = array_unique($image_arr);

Then

print_r($uniq_image_arr); //produces the following result

Array ( [0] => 03578975.jpg [2] => 03578975c.jpg [4] => 03578975b.jpg [6] => 03578975e.jpg [8] => 03578975f.jpg [10] => 03578975a.jpg [12] => 03578975d.jpg [14] => 03578975g.jpg [15] => 03578975g.jpg )

As you can see, after array_unique, all of the duplicates have been removed, except the last to index positions that contain a duplicate '03578975g.jpg'. I don't know why it's not removing the last duplicate, any ideas? Any more info I could give to help debug? (I understand array_unique is checking for both type and value '==='. Both should be the same.) Thanks!

The only temporary fix I can think of is to write the values to a file, then apply the Linux 'uniq' command to the file, then bring the values back in. That seems like a terrible hack though :)

Re: array_unique producing unexpected results... any help?

Posted: Tue Mar 18, 2008 8:21 pm
by John Cartwright
try a var_dump() instead of print_r, sounds like some extra whitespace.

Re: array_unique producing unexpected results... any help?

Posted: Sat Mar 22, 2008 3:05 am
by masterkrang
Hey, thanks a lot, your comment helped me solve the problem. After viewing the contents of the array with var_dump, I was able to determine that the final image had a '\r' (return) character in it. The images were grabbed out of a flat file database, so the last column in the record, which happened to be the last image record in the array, ended up with a return character. What I did was run the trim() function on the image url's before putting them into the array. After that, the unique function ran without a hitch :) Thanks again.