I'm creating a Q&A website, Something like SO. Now I need to print a "check" icon (to specify accepted answer) next to every answer. Now there are some conditions:
- Is the current user logged?
- Is the current user the author of the question?
- Is there any accepted answer?
And some other cases.
Actually, I implemented that. But I did it using a lot of nested if
-statement and seems to me really unoptimized. Now I want to know is there any better algorithm to write this code?
$results = $stm->fetchAll(PDO::FETCH_ASSOC); // Fetching all answers
foreach ($results as $result){
if ($_SESSION['id'] == $author_id){ // User is logged
if($result['id'] == $AcceptedAnswerId){ // There is accepted answer
$AcceptAnswerIcon = "<a href='#'>
<i style='color: green;' class='fa fa-check'></i>
</a>";
} else { // There isn't accepted answer
$AcceptAnswerIcon = "<a href='#'>
<i style='color: gray' class='fa fa-check'></i>
</a>";
}
}
elseif ($_SESSION['id'] !== $author_id) { // User isn't logged
if($result['id'] == $AcceptedAnswerId){ // There isn accepted answer
$AcceptAnswerIcon = "<i style='color: green;' class='fa fa-check'></i>";
} else { // There isn't accepted answer
$AcceptAnswerIcon = null;
}
}
else {
$AcceptAnswerIcon = null;
}
// ... I will use $AcceptAnswerIcon in here and mix it with answer structure
} // End of "foreach" block