Jump to content

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.