1

I am not good with php I'll be honest. I had a snippet of code from a while back that actually works now but it randomizes the text instead of doing line by line 1 at a time. I need it to be balanced when rotating. Here is what I have:

$test = file('my_txt_file.txt'); $randomized = $test[ mt_rand(0, count($test) - 1) ]; 

Then I can echo $randomized as needed throughout my page. But like I said my issue is I DO NOT want it random, but line by line in order, looping endlessly. Any thoughts on this??

1
  • When do you want the value to change? On each page load? Commented Mar 31, 2011 at 12:13

4 Answers 4

2

Use iterators from SPL: http://us.php.net/manual/en/class.infiniteiterator.php

$test = file('my_txt_file.txt'); // this allows you to loop endlessly (vs. ArrayIterator) $lineIterator = new InfiniteIterator($test); // ... // Later where you want to use the current line echo $lineIterator->current(); $lineIterator->next(); // prepare for next call 

This method let's you arbitrarily access the array without having an explicit list. So you can write the echo line (or some variation) anywhere. Should be better than a for loop from what I understand about your question.

If you don't have SPL, obviously you would have to define your own iterator class to use this method.

Sign up to request clarification or add additional context in comments.

Comments

1

If you don't have SPL, you could do this:

$test = file('my_txt_file.txt'); $test_counter = 0; // Whenever you want to output a line: echo $test[$test_counter++ % count($test)]; 

Will work for over 2 billion iterations.

2 Comments

Good alternative to my answer!
@Matt - Would have added as comment to your answer, except that format for comments is too limited.
0

you can use a for loop:

for($i = 0; $i < count($test); $i++){ echo $test[$i]; //display the line if(($i + 1) >= count($test)) $i = -1; //makes the loop infinite //if you don't want it to be infinite remove the above line } 

Comments

0
<?php $test = file('test.txt'); for ($i = 0; $i < count($test); $i++) { echo $test[$i]; if ($i == (count($test)-1)) { $i = -1; } } ?> 

1 Comment

nice going repeating answers :-p (im sure u ddnt mean it ^_^)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.