$files = glob("../../users/$username/posts/*");
foreach( $files as $eachfile )
{
echo basename($eachfile); //this is current basename
echo "?"; //previous basename how will be?
echo "?"; //next basename how will be?
}
How I can echo the next and the previous basename of the loop, on the same loop, i mean without the php do again the foreach as you can see in the example.
maybe you could do something like:
$files = glob("../../users/$username/posts/*");
for($i = 1; $i < count($files) - 1;$i++)
{
echo basename($files[$i]); //this is current basename
echo basename($files[$i - 1]);
echo basename($files[$i + 1]);
}
Simplify first
To get the loop right, it could be easier to see the three values as looking back only, not ahead:
Instead of "need the previous and next basename", you can simplify the problem as "need the previous two basenames".
Save old values
Now, you can save the previous two basenames in two variables.
The current basename can be saved at the end of the loop as the previous one for the next loop.
The previous basename will be the second previous one in next iteration.
Rename to make next part easier
The simplification was useful for this part, but it may be easier for the later parts of the algorithm to have previous and next basename. So, if that helps, you could now rename the variables curent, previous and previous2 to next, curent, and previous.
In pseudocode (I don't know php):
prev = files[0]
curr = files[1]
next = files[2]
for (i = 2...files.length) {
next = files[i]
echo prev
echo curr
echo next
prev = curr
curr = next
}
Related
What I'm looking for is looking for logic that allows you to print horizontal rulers between content, except for the last content block, which you do NOT want to close with a horizontal ruler.
I have this code to loop the number from 1 to 10 and I have this if inside to check if number is stored in database.
for($i=1;$i<=10;$i++){
if($i == $class->Check($i)){
echo $i;
echo "<hr>"; // if not the last!
}
}
I want to check here if it is the last data with the if condition not the loop, so if we got from if and the loop the numbers 2,3,4,7, I want to check with another if condition if it is the last number and print something.
Notice -> the for loop numbers isn't the same it's a variable this is just an example.
What is the code for (I have this loop and when if condition is true it print something then a hr tag, but I don't want the lase print to print a hr tag so I want to check if it is the last print with if condition to stop it from printing the tag).
In your condition, you can save your output in an array, instead of displaying it immediatly, and then, you can use it later, by checking if you are at the last value :
$MyOutput = [];
for($i=1;$i<=10;$i++) {
if($i == $class->Check($i)){
$MyOutput[] = $i;
}
}
for($i = 0, $len = count($MyOutput); $i < $len; $i++)
{
echo $MyOutput[$i];
if ($i == $len - 1) // are we at the last element ?
{
// your special message for the last element
}
}
So I've got a couple of questions that I'm hoping someone will be able to help me with.
Firstly, I'm trying to create a page which parses information and organizes it by the hour into a table. At the moment my script parses the information with Simple HTML Dom and creates a text file for each hour called "hour_%time%.txt" (e.g. hour_02.txt, hour_14.txt, hour_22.txt). Each file will contain the parsed information as a table row.
How would I go about only using the files with times earlier than the current hour, so if the current hour was 9am, only files ending with equal to or less than 09 would be used? I was trying to use either explode or preg_match but I couldn't get it to work.
My code at the moment looks like so:
date_default_timezone_set('UTC');
$currentHour = date('H');
$cache_file = 'cache/hour_'.$currentHour.'.txt';
$data = '<tr><td>'.date('H:00').'</td><td>'.$firmato_count.'</td><td>'.$inviato_count.'</td><td>'.$positive_count.'</td><td>'.$negative_count.'</td></tr>';
file_put_contents($cache_file, $data);
echo '<table class="table"><tbody>';
echo '<tr><th>Time</th><th>Firmato</th><th>Inviato</th><th>Positive</th><th>Negative</th></tr>';
$files = glob("cache/hour_*.txt");
foreach($files as $txt){
$hourlyfile = file_get_contents($txt);
echo $hourlyfile;
}
echo '</table></tbody>';
And secondly, I'm fully aware this isn't the best way to do this but I couldn't figure out a better way myself. Can anyone suggest a more efficient way to store the parsed data and access it? Is it possible to use a single file? I did consider appending the same file however as my page will update frequently it ended up adding multiple lines of data for the same hour. Each file contains a string like so:
<tr><td>10:00</td><td>21</td><td>58</td><td>4</td><td>43</td></tr>
Any help is appreciated.
First convert your String of the hour to a number
[PHP]
$currentHour = intval($currentHour);
next compare
if($currentHour <= 9){ // < for less and <= for less and equal
doStuff
}
This only will display the file of the exact hour. Tell me if doesn't work for edit it.
date_default_timezone_set('UTC');
$currentHour = intval(date('H'));
$cache_file = 'cache/hour_'.$currentHour.'.txt';
$data = '<tr><td>'.date('H:00').'</td><td>'.$firmato_count.'</td><td>'.$inviato_count.'</td><td>'.$positive_count.'</td><td>'.$negative_count.'</td></tr>';
file_put_contents($cache_file, $data);
echo '<table class="table"><tbody>';
echo '<tr><th>Time</th><th>Firmato</th><th>Inviato</th><th>Positive</th><th>Negative</th></tr>';
$files = glob("cache/hour_*.txt");
if($currentHour == $currentHour){
foreach($files as $txt){
$hourlyfile = file_get_contents($txt);
echo $hourlyfile;
}
}
echo '</table></tbody>';
I ended up creating a variable called $globSearch and used if/elseif to create a search string based on the current hour. My code now looks like this:
date_default_timezone_set('UTC');
$currentDate = date('d/m/Y');
$currentHour = intval(date('H'));
$cache_file = 'cache/hour_'.$currentHour.'.txt';
$data = '<tr><td>'.date('H:00').'</td><td>'.$firmato_count.'</td><td>'.$inviato_count.'</td><td>'.$positive_count.'</td><td>'.$negative_count.'</td></tr>';
file_put_contents($cache_file, $data);
echo '<table class="table"><tbody>';
echo '<tr><th>Time</th><th>Firmato</th><th>Inviato</th><th>Positive</th><th>Negative</th></tr>';
if ($currentHour <= 9) {
$globSearch = "{cache/hour_[0][0-".$currentHour."].txt}";
} elseif ($currentHour >= 10 && $currentHour <= 19) {
$splitInt = str_split($currentHour);
$globSearch = "{cache/hour_[0][0-9].txt,cache/hour_[1][0-".$splitInt[1]."].txt}";
} elseif ($currentHour >= 20 && $currentHout <= 23) {
$splitInt = str_split($currentHour);
$globSearch = "{cache/hour_[0][0-9].txt,cache/hour_[1][0-9][2-".$splitInt[1]."].txt}";
}
//$files = glob("{cache/hour_[0][0-9].txt,cache/hour_[1][0-3].txt}", GLOB_BRACE);
$files = glob($globSearch, GLOB_BRACE);
foreach ($files as $txt) {
$hourlyfile = file_get_contents($txt);
echo $hourlyfile;
}
echo '</table></tbody>';
Thanks for replying Ruben and COOLGAMETUBE, much appreciated.
I know I have done this in Javascript once, but how can I make it in PHP?
Basically I want to do this:
if (empty($counter)){
$counter = 1;
}else{
"plus one to $counter" ($counter++?)
}
But it didn't work when I tried. How would I go about doing this?
Thank you :)
EDIT: This is so I can do:
if ($counter == 10){
echo("Counter is 10!");
}
EDIT:
This is all in a "while()" so that I can count how many times it goes on, because LIMIT will not work for the query I'm currently doing.
why the extra if into the while?
i would do this:
$counter = 0;
while(...)
{
(...)
$counter++;
}
echo $counter;
To increment a given value, attach the increment operator ++ to your integer variable and place it within your while loop directly, without using a conditional expression to check if the variable is set or not.
$counter = 1;
while(...){
echo "plus one to $counter";
$counter++;
}
If your counter is used to determine how many times your code is to be executed then you can place the condtion within your while() expression:
while($counter < 10){
echo "plus one to $counter";
$counter++;
}
echo("Counter is $counter!"); // Outputs: Counter is 10!
You're going to have to learn the basics of how PHP outputs to the screen and the other controls along with it.
if (empty($counter)){
$counter = 1;
}else{
echo 'plus one to $counter';
$counter++;
}
Something along those lines will work for you.
PHP is pretty flexible with what you throw at it. Just remember, statements need a semicolon at the end, and if you want to output to the screen, (in the beginning) you'll be relying on echo statements.
Also, when dealing with echo statements, notice the difference between single quotes and double quotes. Double quotes will process any contained variables:
$counter = 3;
echo "plus one to $counter"; // output: plus one to 3
echo 'plus one to $counter'; // output: plus one to $counter
Trying to make it so that the glob function displays only the first 10 results (text files from a folder) and then automatically the next 10 with a next button.
Currently, I used array_slice to display only the first 10, but I'm not sure how to automate the process.
foreach(array_slice(glob("*.txt"),0,9) as $filename) {
include($filename); }
Oh and while I'm at it, if possible, display something like "displaying 1-10" and last/first links. I could probably figure that out myself after I get past the first obstacle, so don't bother with this unless it's a super easy solution.
What you're trying to accomplish is called pagination. From your example, you can dynamically choose which ten you're viewing by setting a variable that determines what number (file) to start at.
Example:
<?php
$start = isset( $_GET['start']) ? intval( $_GET['start']) : 0;
$glob_result = glob("*.txt");
$num_results = count( $glob_result);
// Check to make sure the $start value makes sense
if( $start > $num_results)
{
$start = 0;
}
foreach( array_slice( $glob_result, $start, 9) as $filename)
{
include( $filename); // Warning!
}
If you only want to do increments of 10, you can add a check to make sure $start is divisible by 10, something like this after $start is retrieved from the $_GET array:
$start = ( $start % 10 == 0) ? $start : 0;
Now, for links, all you need to do is output <a> tags that have the start parameter set correctly. You will have to do some logic to calculate the next and previous values correctly, but here is a simple example:
$new_start = $start + 10;
echo 'Next';
Edit: As the comments above suggest, you probably do not want to include() these files, as include() will attempt to interpret these files as PHP scripts. If you just need to get the contents of the text files, use file_get_contents instead.
I have set to constants, a start year and an end year,
so i have built a while loop on the condition that
if the start year is < than the current year increment until true.
the problem i have is that instead of it going up like this:
1999,2000,2001,2002,2003,2004
it goes like:
1999,2001,2003,2005,2007,2009
Here is my code:
function yearCount()
{
$yearBegin = START_YEAR;
$yearCurrent = CURRENT_YEAR;
while($yearBegin < $yearCurrent){
echo "<option value=\"".$yearBegin++."\">".$yearBegin++."</option>";
}
}
any ideas would be highly appreciated.
You are incrementing the value twice:
echo "<option value=\"".$yearBegin++."\">".$yearBegin++."</option>";
Each $yearBegin++ increments it by one.
Use a for loop instead:
for ($yearBegin = START_YEAR; $yearBegin < CURRENT_YEAR; $yearBegin++)
{
echo "<option value=\"".$yearBegin."\">".$yearBegin."</option>";
}
Using a for loop is usually the way to do this,
for($year=START_YEAR;$year<=CURRENT_YEAR;$year++)
{
//User the $year here
}
your problem with the code is that your calling $yearBegin++ 2 times within the while loop, causing it to increment twice.
using the for loop is much cleaner then as incrementing is done within the expression for you
function yearCount()
{
$yearBegin = START_YEAR;
$yearCurrent = CURRENT_YEAR;
while($yearBegin < $yearCurrent){
$this_year = $yearBegin++;
echo "<option value=\"".$this_year."\">".$this_year."</option>";
}
}
use only one time ++ , increment
echo "<option value=\"".$yearBegin."\">".$yearBegin++."</option>";
You increment $yearBegin twice, one time in the value part, one time in the display part ...
You need to change it so it only increments once
You increment it twice, once setting it as a value, and the second time displaying it in option tag