Reputation: 5
I am new to PHP and I would like to know the correct way to display error in index.php but only if there are errors otherwise it does nothing.
The page index.php send the form to login.php if there are errors it return the error to index.php like this:
index.php?error=1
Then in index I have the follow code but it feels like the page got slow
<?php
if ($_GET['error']==1){echo "We show error 1 ...";}
if ($_GET['error']==2){echo "We show error 2 ...";}
if ($_GET['error']==3){echo "We show error 3 ...";}
?>
How can I fix it the correct way? Some uses the if isset but I dont know how to use this funtion it give me errors
Upvotes: 0
Views: 2598
Reputation: 12505
Any time you have repetition like you have presented in your example, try using a function
or a storage array
. Though your code probably isn't going much slower, try something like this:
<?php
// List of errors. If you do it this way, you can keep
// adding errors without adding if/else
$error[1]= "We show error 1 ...";
$error[2]= "We show error 2 ...";
$error[3]= "We show error 3 ...";
// Check if set
if(isset($_GET['error']) && isset($error[$_GET['error']]))
echo $error[$_GET['error']];
?>
Upvotes: 1
Reputation: 639
isset
in PHP from the documentation is to determine if a variable is set and is not NULL. Refer here
This is how you can use it in your case.
Assuming the URL is something like index.php?error=1
Then you could use:
if( isset($_GET['error']) ){
if( $_GET['error'] == 1 ) {echo 'Error 1!';}
elseif( $_GET['error'] == 2 ) {echo 'Error 2!';}
elseif( $_GET['error'] == 3 ) {echo 'Error 3!';}
}
Using elseif
can terminate the execution once you reach any error code. For example, if you have error=2
it will not check if the error=3
thus makes the execution faster. But as Scopey mentioned above, the difference of execution time for this kind of thing is actually something that you don't have to worry.
Hope this helps. Thank you.
Upvotes: 0
Reputation: 35337
isset isn't provided anywhere in your code, but this also presents an opportunity to introduce you to switch.
if (isset($_GET['error'])) {
switch($_GET['error']) {
case 1:
echo "We show error 1...";
break;
case 2:
echo "We show error 2...";
break;
case 3:
echo "We show error 3...";
break;
}
}
Instead of using different if's, you can combine it all into one switch. This is similar to using elseif but neater (in my opinion).
Upvotes: 1