I have a vote system that allows users to vote for items. Right now I am doing it by checking first if the user is logged in and then checking to see if they have already voted. I am wondering if there is a better way of doing this as I have been told that nested if statements are something to avoid.
My code:
if ($loggedIn) {
if($row['voted']){
You Already voted
}else{
<a href="#">Agree</a>
}
}else{
Please Register
}
Nested if( ... ){ ... }else{ ... }
statements are fine, so long as they are logical and easy to read/maintain. Another option is to review the logic of your arguments and see if they can be expressed in a simpler fashion.
For example, your provided code could be expressed as:
if( !$loggedIn ){
echo 'Please Register';
}elseif( $row['voted'] ){
echo 'You Already voted';
}else{
echo '<a href="#">Agree</a>';
}
It's not quite that simple. Your example is simple but other situations are not. In your example it's easy to follow what's going on so nested if statements are fine to use. In more complicated code, deeply nested statements make for difficult to maintain code. As with many things programming it's going to vary from situation to situation and you'll need to decide on a case by case basis.
In general, it's fine. You want to avoid overly complex nested if statements
In this case it is fine, in fact in most cases it is. The problem only occurs when you have many nested in many and so it can become hard to read and you may forget something, but that's readability, there is nothing wrong in the logic for using nested if statements.