Very new to PHP, just trying to set up a ternary statement for a news feed page.
The goal:
If the posting date of the story is greater than 24 hours, show the number of days ago it was posted. Ie, if the story was posted 48 hours ago, show 2 days.
Else if the posting date of the story was within the last 24 hours, show the number of hours ago it was posted. Ie if it was posted 9 hours ago, display 9 hours.
My current code is this:
foreach($result as $news_item)
{
$news_item_timestamp = strtotime($news_item["DateInserted"]);
$just_updated = ((time() - $news_item_timestamp) < 3600) ? "<span class='just_updated'>NEW</span>" : "";
$link = "news-details.php?news_item_id=".$news_item["NewsItemId"]."&feed=".$news_item["FeedId"];
echo "<a href='$link'><div class='news_item'>";
echo "<div class='headline'>$just_updated ".$news_item["Headline"]."</div>";
//the line below is the code in question
echo "<div class='dateline'>".date("l, F j, Y", $news_item["ThisRevisionCreated"])."</div>";
echo "</div></a><div class='cleardiv'></div>";
}
So as you can see there is no ternary operator setup. But I'm assuming line 8 is where I need to throw one in.
Any suggestions are appreciated.
In PHP, as with most programming language, you'll need to run through logical things like this in your head all the time. The steps to solving this issue would normally follow a three step process:
Since you've already thought through the first step, the next is to think about how the logic may come to life through real life code. Setting up a psuedo-code example, I'd do something like the following.
if timeElapsed < 24 hours
print hoursElapsed
else
print daysElapsed
Note that we didn't quite set up the ternary operator, but we have the bare minimum and can easily convert the above to PHP and fit into the code environment that you've already set up. Thinking through this, we have some variables that we'd need to define, but we can do that in the PHP:
$elapsedTime = time() - $news_item_timestamp; //difference in time from post to now
$relativeDate = ($elapsedTime < 86400) ? round($elapsedTime/3600) . " minutes ago" : round($elapsedTime / 86400) . " days ago";
// 86400 seconds = 60 seconds * 60 minutes * 24 hours = 1 day
// 3600 seconds = 60 seconds * 60 minutes = 1 hour