Jump to content

Is this possible?


LemonInflux

Recommended Posts

Is there a way to create a foreach( loop, whereby every 3rd value does something different. For example, I have a file called test.txt, that contains this:

 

a
b
c
d
e
f
g
h
i
j
k
l
m
n
o
p
q
r
s
t
u
v
w
x
y
z

 

Now, say I create a loop like:

 

<?php
$file = file_get_contents('test.txt');
$letter = explode('\n', $file);
foreach($letter as $loopletter){
echo ('<td>'.$loopletter.'</td>');
}
?>

 

Now, what if I wanted every third value to do this:

 

echo ('<td>'.$loopletter.'</td></tr><tr>');

;

 

Is this possible?

Link to comment
https://forums.phpfreaks.com/topic/70907-is-this-possible/
Share on other sites

Many ways:

<?php
$file = file_get_contents('test.txt');
$letter = explode('\n', $file);
$tot = count($letter);
echo "<table><tr><td></td></tr>";
for($i=0;$i<$tot;$i+3){
   echo ('<tr><td>'.$letter[$i+1].'</td><td>'.$letter[$i+2].'</td><td>'.$letter[$i+2].'</td></tr>');
}
echo "</table>";
?>

Link to comment
https://forums.phpfreaks.com/topic/70907-is-this-possible/#findComment-356449
Share on other sites

Do you want to output a table to screen, or actually output a doc? (.txt, .csv, .xls, etc.)

 

You can do either or both...

 

Simply use the strategy that rarebit employed: a simple counter that keeps track of every third event, but don't forget that you will have to put some closes clauses that add what is appropriate depending on the column count when the data runs out.

Link to comment
https://forums.phpfreaks.com/topic/70907-is-this-possible/#findComment-356452
Share on other sites

@LemonInflux,

 

People are asking for additional information because many times what a poster is asking for is not really what they are wanting. So, by explaining what you are trying to accomplish will allow us to provide a best practice solution because the process you are asking to solve might not be the best.

 

But, a simple answer is something like this:

 

<?php

$step = 1;
foreach ($arrayVar as $value) {

  if ($step<3) {
    //Do this
    $step++;
  } else {
    //Do alternative
    $step = 1;
  }

}

?>

Link to comment
https://forums.phpfreaks.com/topic/70907-is-this-possible/#findComment-356535
Share on other sites

Archived

This topic is now archived and is closed to further replies.

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