0

in this below code i want to fill array with for repeator. echo can display and not have problem but. my array could not fill by for.

<meta charset='UTF-8' />
<?php
error_reporting(1);
$handle='A-file.txt';
$handle = file_get_contents($handle);
$lines = explode(PHP_EOL,$handle );
$names = array();
for( $i = 0; count($lines)-1 ; $i+=4 )
{
    $names[]= $lines[$i];

    //$names= $lines[$i];
    //$names[]+= $lines[$i];
    //echo $lines[$i];
}
print_r($names);
?>
2
  • 1
    for( $i = 0; $i <= count($lines)-1 ; $i+=4 ) Commented Jan 21, 2014 at 9:37
  • 3
    $i<count($lines)-1; Commented Jan 21, 2014 at 9:37

5 Answers 5

4

You've forgotten the comparison with $i:

for( $i = 0; $i <= count($lines)-1 ; $i+=4 )
{
    $names[]= $lines[$i];

    //$names= $lines[$i];
    //$names[]+= $lines[$i];
    //echo $lines[$i];
}
Sign up to request clarification or add additional context in comments.

Comments

1

Try this, You have missed to add $i < count($lines)-1

for( $i = 0; $i < count($lines)-1; $i+=4 )

instead of

for( $i = 0; count($lines)-1 ; $i+=4 )

Comments

1

Check the file has more than 4 lines, and the for finishes with that condition maybe will be an eternal loop.

Comments

0

This is perhaps just a tip to solve the problem more likely.

Use file() (http://php.net/file) to directly read a file's content into an array (so you don't need to do it manually with more lines then needed) and iterate over these lines using foreach($lines as $i => $line) {...} instead. To skip lines you can do:

if($i % $nthElem !== 0) continue;

You could even do it in one turn:

foreach(file($yourFile) as $i => $line){
   if($i % 4 !== 0) continue;

Comments

-1

Always optimize your for loop by putting count function out of for loop and store it in a variable. Use that in the loop

$count = count($lines);
for( $i = 0; $count-1 ; $i+=4 ) {

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.