Jump to content

better coding


n3p3

Recommended Posts

how can i rewrite the code below in a more proffessional way. I mean avoiding repetation, using ternary operator in one line or at least two.

if (($lastNotified) < strtotime($timeAdded) {
if ($i == $count) {
	echo '<li class="unread last">'.$row['message'].'</li>';
}
else {
	echo '<li class="unread">'.$row['message'].'</li>';
}
} else {
if ($i == $count) {
	echo '<li class="last">'.$row['message'].'</li>';
}
else {
	echo '<li>'.$row['message'].'</li>';
}
}

Link to comment
https://forums.phpfreaks.com/topic/163595-better-coding/
Share on other sites

Sorry, my mistake that I forget the last parentheses.

 

actually what I want to do is to combine if blocks.

example;

$class = ($lastNotified < strtotime($timeAdded)) ?'undread':'';
$class .= ($i == $count)?' last':'';
echo '<li'.(!empty($class))?' class="$class"':''.'>'.$row['message'].'</li>';

 

but, since I've been working with more than one class I couldn't make it work.

any suggestions?

thank you

Link to comment
https://forums.phpfreaks.com/topic/163595-better-coding/#findComment-863203
Share on other sites

I think this is what you mean:

 

if (($lastNotified) < strtotime($timeAdded) {
   echo ($i == $count) ? '<li class="unread last">'.$row['message'].'</li>' : '<li class="unread">'.$row['message'].'</li>';
} else {
   echo ($i == $count) ? '<li class="last">'.$row['message'].'</li>' : '<li>'.$row['message'].'</li>';
}

 

I've never used a ternary operator with echo before, but should work! Personally though, for easier reading and future development I prefer to use ternary operators as little as possible.

Link to comment
https://forums.phpfreaks.com/topic/163595-better-coding/#findComment-863215
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.