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);
?>
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];
}
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 )
Check the file has more than 4 lines, and the for finishes with that condition maybe will be an eternal loop.
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;
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 ) {
}