3
05/11/2024 3:26 pm
Emne starter
You will be given a string representing a username. The password will be that username reversed. Until you receive the correct password print on the console "Incorrect password. Try again.". When you receive the correct password print "User {username} logged in." However on the fourth try if the password is still not correct print "User {username} blocked!" and end the program.
Examples:

2 Svar
3
05/11/2024 3:27 pm
My solution:
<?php
$user = readline();
$length = strlen($user); //the length of the string
$pass = '';
for ($i = $length - 1; $i >= 0; $i--) {
$pass .= $user[$i];
}
$attempts = 0;
while ($attempts++ < 6) {
$input = readline();
if ($input === $pass) {
echo "User $user logged in." . PHP_EOL;
break;
}
if ($attempts === 4) {
echo "User $user blocked!" . PHP_EOL;
break;
} else {
echo "Incorrect password. Try again." . PHP_EOL;
}
}
1
05/11/2024 3:28 pm
Instead og using reversed for loop, you can use strrev() PHP function/method to reverse the string (on line 4):
<?php
$user = readline();
$pass = strrev($user);
$attempts = 0;
while ($attempts++ < 6) {
$input = readline();
if ($input === $pass) {
echo "User $user logged in." . PHP_EOL;
break;
}
if ($attempts === 4) {
echo "User $user blocked!" . PHP_EOL;
break;
} else {
echo "Incorrect password. Try again." . PHP_EOL;
}
}
