Frank Lucas Frank Lucas - 2 years ago 81
PHP Question

PHP prevent duplicates when building an array

I am building an array like this: (this happens in a loop)

$IDs[] = ID;

But I want to prevent that the same ID is being entered mulitple times, is there any way I can prevent this from happening?

Many thanks in advance!!

Answer Source

Use array_unique. It will remove duplicates.

It will not prevent you from adding duplicates but when your looping is done you can just do:
$arr = array_unique($arr);

EDIT: Jay gave a good solution too in the comments.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download