PHP – Incrementing element with the same name.

558fe5180e0e8fc922d31c23ef84d240

If you download multiple files with the same name, a number is automatically added to the file name, for example: filename(1), filename(2) etc..

What I am trying to do is when I am creating a name and there is already a same one, the name I create to appear in the list as: name(1), name(2) etc.

This is the code that I use now that only creates: name and name (1), then I get this error when trying to create the next same name, example: name (1) already exists in your list., but I shouldn't get that error and should create the next name in the list: name (2) etc..

$deviceUser = "07NAV" . $var;
$sameNames = $mktApi->comm("/ppp/secret/getall", array(
    ".proplist" => ".id",
    "?name" => $deviceUser
));

$i = 0;
if($sameNames) {
    $i++;
    $mktApi->comm("/ppp/secret/add", array(
        "name" => $deviceUser . " ($i)",
        "remote-address" => $IPs[$ipAddress],
        "password" => $devicePass,
        "service" => "pppoe",
        "comment" => $fullAddress
    ));
}

Also, I've tried using this one:

$i = 0;
if($sameNames) {
    for($i = 0; $i < 99999; $i++) {
        $i++;
        $mktApi->comm("/ppp/secret/add", array(
            "name" => $deviceUser . " ($i)",
            "remote-address" => $IPs[$ipAddress],
            "password" => $devicePass,
            "service" => "pppoe",
            "comment" => $fullAddress
        ));
    }
}

but when I create only one name in my list, automatically creates X names and I do not want that.
I've been searching for help on other communities too and somebody provided me this code, but I still get the same error ("user with same name already exists"):

// Start your update here:
$i = 0;
$deviceUser = $deviceUserOriginal = "07NAV" . $var;
$sameNames = false;
do {
    // First - check if a dupe exists...
    $sameNames = $mktApi -> comm("/ppp/secret/getall", array(
        ".proplist" => ".id",
        "?name" => $deviceUser
    ));

    // Second - update and prepare for rechecking ...
    if($sameNames === true) {
        $i ++;
        $deviceUser = $deviceUserOriginal . "(". $i .")";
    }

    // Finally, below, if check failed, cycle and check again with the new updated name...
}
while($sameNames === true);

// Finally, tidy up.
// If you need the original value of $deviceUser you can retain it.
unset($i, $deviceUserOriginal);

// Continue your script here:
$mktApi -> comm("/ppp/secret/add", array(
    "name" => $deviceUser,
    "remote-address" => $IPs[$ipAddress],
    "password" => $devicePass,
    "service" => "pppoe",
    "comment" => $fullAddress
));