Frank Lucas
Frank Lucas

Reputation: 592

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!!

Upvotes: 0

Views: 4385

Answers (2)

DocRattie
DocRattie

Reputation: 1423

$IDs[$ID] = $ID;

This is a simple way to ensure that every ID is only once in your array.

Even thought array_unique works as well, I think this is a faster and easier way.

Upvotes: 2

Andreas
Andreas

Reputation: 23958

Use array_unique. It will remove duplicates.

http://php.net/manual/en/function.array-unique.php

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.

Upvotes: 3

Related Questions