0

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

3

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks didn't know it existed!
@FrankLucas No problem. I updated with one more line in my answer
Is there a way I can reset the keys? I now get [0] and [3] as keys it should be [0] and [1] :)
@FrankLucas Maybe this. ca2.php.net/manual/en/function.array-values.php not sure though
@FrankLucas To reset keys use array_values() function.
2
$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.

1 Comment

also note that array_unique() will retain the FIRST item in the array, while this technique will ensure that the latest entry is in the array. In many cases you want the most recent entry, not the oldest.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.