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
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
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
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

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