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>';
}