Adding, removing, and changing user names and passwords in .htpasswd with PHP
Here is my version based on two personal preferences: I hate scroll bars and I hate repititions. Hence I prefer everything typed once and also I like my code being fully visible in the default code area on Stack Overflow.

for this reason I removed that double spacing which just hurts my eyes
also I removed the try catch which is a cargo cult code that makes no sense. I was never able to understand what's the point in writing a try catch that's the only job is to echo the error message when without a try catch PHP will do exactly the same - echo the error message
also I removed the code repetitions such as mentioning the filename in a dozen places
also I changed the algorithm, to make it add a user line only once
I also removed that uncertainty when we can't make our mind whether we are working with an array or with a text
I also changed the function name as it doesn't only add a user
and some other improvements such as following the HTTP guidelines and the ability to choose the hashing algorithm without using inline comments

here it goes
&lt;?php
$filename = &quot;.htpasswd&quot;;
if (isset($_POST['user'])) {
    manage_htpasswd($_POST['user'], $_POST['pass'], $filename);
    header(&quot;Location: &quot;.$_SERVER['REQUEST_URI']);
    exit;
}
function manage_htpasswd($user, $pass, $filename, $algo = 'crypt_apr1_md5')
{
    $lines = file($filename);
    foreach ($lines as $i =&gt; $line) {
        $existing_user = explode(':', $line);
        if ($existing_user[0] === $user) {
            unset($lines[$i]);
            break;
        }
    }
    if ($pass) {
        $lines[] = &quot;$user:&quot; . $algo($pass) . PHP_EOL;
    }
    file_put_contents($filename, $lines);
}
?&gt;
&lt;form method=&quot;post&quot;&gt;
    User: &lt;input type=&quot;text&quot; name=&quot;user&quot;&gt;&lt;br&gt;
    Pass:&lt;input type=&quot;text&quot; name=&quot;pass&quot;&gt;&lt;br&gt;
    &lt;input type=&quot;submit&quot;&gt;
&lt;/form&gt;
&lt;h4&gt;&lt;?= $filename ?&gt;:&lt;/h4&gt;
&lt;pre&gt;
&lt;?= file_get_contents($filename) ?&gt;
&lt;/pre&gt;