I suggest first creating an array of all existing identifier values (which is a single xpath request), and then you check it:
$id = 0; while(isset($ids[$id])) { $id++; } echo $id;
Creating such a list trivially launches xpath on SimpleXML, however it can be easily ported to DOMXPath, as well as using iterator_to_array :
<?php $buffer = <<<BUFFER <?xml version="1.0"?> <catalog> <book id="0"> <author>Gambardella, Matthew</author> <title>XML Developer Guide</title> <genre>Computer</genre> <price>44.95</price> <publish_date>2000-10-01</publish_date> <description>An in-depth look at creating applications with XML.</description> </book> <book id="1"> <author>Ralls, Kim</author> <title>Midnight Rain</title> <genre>Fantasy</genre> <price>5.95</price> <publish_date>2000-12-16</publish_date> <description>A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world.</description> </book> </catalog> BUFFER; $xml = simplexml_load_string($buffer); $ids = array_flip(array_map('intval', $xml->xpath("/*/*/@id")));
Interactive demo
In addition, I suggest you not use 0 (zero) as the ID value.
hakre source share