How To - PHP Array Difference

Working on a project I had the need to look through a list of values, or in this case "id" numbers to find missing numbers in the sequence. The goal was to re-use an id that was not in use or simply increment to the next one. Here is a simple example of the code I ended up using.

The logic was to create an array of "id" values from my source data. Then defining a reference array from 0 to the maximum "id" value found in the data. Using the array_diff function to create an array of values present in reference range, but absent in the existing data. My next value would be the minimum value of the missing IDs. If all values were accounted for, then I would simply choose the next numerical ID.

    $used_ids = array(0,1,2,3,4,6) 
    $range_ids = range(0,max($used_ids));
    $unused_ids = array_diff($range_ids,$used_ids);
    if ($unused_ids) {
      $new_id = min($unused_ids);
    } else {
      $new_id = max($used_ids)+1;
    }