I have a log.txt file with these kind of datas:
2022-08-25 13:16----------817650|xx:xx:xx:xx:xx:xx|user1|10
2022-08-25 13:16----------817856|xx:xx:xx:xx:xx:xx|user1|5
I would like to compare the last values (10 and 5) from the last two lines, but I got stuck in recognizing the lines.
<?php
$textCnt = "./log.txt";
$contents = file_get_contents($textCnt);
$arrfields = explode( "|" , $contents);
echo $arrfields[3];
?>
I got this:
10 2022-08-25 13:16----------817856
instead of
10
My Answer:
You can use the PHP `file()` function to read the contents of the log.txt file into an array, and then use the `explode()` function to split each line by the separator "|__". Here's an example code snippet to achieve this:
php
// Read the contents of the log.txt file into an array
$lines = file('log.txt');
// Get the last two lines from the array
$last_line = end($lines);
$second_last_line = prev($lines);
// Split the last two lines by the separator "|__"
$last_line_parts = explode('|__', $last_line);
$second_last_line_parts = explode('|__', $second_last_line);
// Get the last values from the last two lines
$last_value = end($last_line_parts);
$second_last_value = end($second_last_line_parts);
// Compare the last values
if ($last_value > $second_last_value) {
echo "The last value is greater than the second last value.";
} elseif ($last_value < $second_last_value) {
echo "The last value is less than the second last value.";
} else {
echo "The last value is equal to the second last value.";
}
This code snippet reads the log.txt file, splits the last two lines by the separator "|__", and compares the last values from the last two lines. You can modify the comparison logic as needed for your specific requirements.
Rate this post
4 of 5 based on 6086 votesComments