Prevent creating duplicate entries in PHP

The best approach would be to create a GUID, rather than an integer. PHP has built-in methods to create these unique codes.

If you are inserting into a database, I would think that the most robust approach would be to create a primary key, and insert your entries one at a time. Since the DB call will error if you try to insert a duplicate ID, that’s an appropriate place to check for an error and choose a different ID if you need to – although if you use a GUID, the chances of duplication are already negligible.


So if I understand what you are trying to do correctly, you want to create an array of random arrays of user ids, which are integers between 1-1000, where no two ids are repeated.

I am assuming that performances is not a big issue, since this sounds like test/dummy data. So the simplest way, in my opinion, would be to avoid having to test for an existing id on each id creation, and just shuffle your array.

So, you start with an array of 1000 ids, and then you loop through x number of times, shuffle the array, and slice off a random number of ids from the beginning of the array. Here is some code I have tested. It outputs what I think you want to create.

$ids = array();
$commentIds = array();
$numIds = 1000;
$numComments = 10;
for($i=0; $i<$numIds; $i++)
    $ids[$i] = $i;
for($s=0; $s<$numComments; $s++)
    $num = mt_rand(1,10);
    $commentIds[$s] = array_slice($ids,0,$num);

Is that what you mean?

Browse More Popular Posts

Leave a Comment