简体   繁体   中英

PHP fill array into for

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 )

检查文件是否有4行以上,并且该条件的结束可能是一个永恒的循环。

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 ) {

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM