Reputation: 145
I have a file (txt) with the following contents:
user1 2019-11-14 10:48:01
user2 2019-11-10 11:38:25
user3 2019-11-15 09:45:30
user4 2019-11-12 00:15:01
user5 2019-11-15 00:15:01
I want to count rows that are 24 hours befor of server time. Unfortunately, I did not succeed by using the following code. Do you have a better solution?
<?php
$lines = file('user.txt');
foreach($lines as $line) {
$section = explode(" ", $line);
$lasttime = "$section[1]"." "."$section[2]";
$timetosecend = strtotime(date("Y-m-d H:i:s"));
$lasttimetosecend = strtotime($lasttime);
$count = 0;
$countitem = $timetosecend-$lasttimetosecend<86400;
if (strstr($line, $countitem)) {
if (($timetosecend-$lasttimetosecend)>86400) {
$count++;
}
}
}
echo $count;
?>
Upvotes: 0
Views: 41
Reputation: 147216
You can simplify your code quite a bit, making use of the limit
parameter to explode
to avoid putting $lasttime
back together, and only computing the current time once. As @NigelRen points out, we can compute the time a day ago and then we only have to check the sign of $timetosecond - $lasttimetosecond
, which is more efficient:
$timetosecond = strtotime("now") - 86400;
$count = 0;
foreach($lines as $line) {
list(, $lasttime) = explode(" ", $line, 2);
$lasttimetosecond = strtotime($lasttime);
if ($timetosecond - $lasttimetosecond < 0) {
$count++;
}
}
echo $count;
Upvotes: 2
Reputation: 2788
Try remove if on the end.
You also need declared $count
out of foreach because you rewrite count to 0 every time in the loop.
<?php
$lines = file('user.txt');
$count = 0; // <-------------- here
foreach($lines as $line) {
$section = explode(" ", $line);
$lasttime = "$section[1]"." "."$section[2]";
$timetosecend = strtotime(date("Y-m-d H:i:s"));
$lasttimetosecend = strtotime($lasttime);
$countitem = $timetosecend-$lasttimetosecend<86400;
if ($countitem) { // <---------- here
$count++;
}
}
echo $count;
Upvotes: 1