Reputation: 165
So I'm trying to create some sort of error messages, code looks like this:
function callError($errorcode, $attempts) {
$errormessage = array(
"0" => "Du har angivit fel lösenord, du har ". $attempts ." försök kvar. Kontrollera att du har skrivit rätt användarnamn.",
"1" => "Ditt konto har låsts, kontakta webmaster för att återställa det.",
"2" => "Användare finns inte, kontrollera att du har skrivit rätt användarnamn."
);
return $errormessage[$errorcode];
}
but when I run the first error message it doesn't work, it won't even show up. On the other hand when I run the other two it works flawless! I've tried to return an array containing $errormessage and $attempts but that doesn't work either.
What am I doing wrong here?
Upvotes: 0
Views: 118
Reputation: 165
The answer was just to remove the numbers that were stringed in the array.
See @fedorqui comment!
Upvotes: 0
Reputation: 3252
Tip: change that to a switch()
statement:
function callError($errorcode, $attempts) {
switch ($errorcode) {
case 0:
return "Du har angivit fel lösenord, du har ". $attempts ." försök kvar. Kontrollera att du har skrivit rätt användarnamn.";
case 1:
return "Ditt konto har låsts, kontakta webmaster för att återställa det.";
case 2:
return "Användare finns inte, kontrollera att du har skrivit rätt användarnamn.";
default:
return "No error associated";
}
}
Upvotes: 0
Reputation:
Try to use a switch with a fallback safety mechnism.
function callError($errorcode, $attempts) {
$output = '';
switch((int)$errorcode) {
case 0:
$output = 'Du har angivit fel lösenord, du har '. $attempts .' försök kvar. Kontrollera att du har skrivit rätt användarnamn.';
break;
case 1:
$output = 'Ditt konto har låsts, kontakta webmaster för att återställa det.';
break;
case 2:
$output = 'Användare finns inte, kontrollera att du har skrivit rätt användarnamn.';
break;
default:
$output = 'SOMETHING WENT WRONG [CUSTOM MESSAGE]'.$errorcode.' : '.$attempts;
break;
}
// Do something more here with your error handling if needed
// Return the output message
return $output;
}
This will force typecast $errorcode
to an Integer. But it doesn't really matter for the default
case, yet it will rule out problems with integers inside a string "1"
.
Upvotes: 1
Reputation: 289755
It seems to be a problem on type of variables.
Make sure you are consistent on this. For example, let's decide we want the values to be int
:
function callError($errorcode, $attempts) {
$errorcode = (int) $errorcode;
$errormessage = array(
0 => "Du har angivit fel lösenord, du har ". $attempts ." försök kvar. Kontrollera att du har skrivit rätt användarnamn.",
1 => "Ditt konto har låsts, kontakta webmaster för att återställa det.",
2 => "Användare finns inte, kontrollera att du har skrivit rätt användarnamn."
);
return $errormessage[$errorcode];
}
Upvotes: 1
Reputation: 4637
Make sure index is String Add
$errorcode = "$errorcode";
as the first line in the func
Upvotes: 0