happyvirus
happyvirus

Reputation: 286

Reading only even line numbers from a file in php

I'm trying to just read even numbered lines from a text file. I know about the modulo(%) operator which I could put in a loop and attain the desired result, but somehow I can't figure out how to put it to use here.

Here is the code I have:

<?php    
$url   = "somedomain/something";
$lines = file('text.txt', FILE_IGNORE_NEW_LINES);

foreach ($lines as $line_num => $line) {

    echo "<br />\n" . "Line #<b>{$line_num}</b>  :" . (htmlspecialchars($line));
    $dom = new DOMDocument;
    $dom->loadHTMLFile($url . $line);
    foreach ($dom->getElementsByTagName('p') as $node) {
        // do stuff with $node
        echo $node->nodeValue, "\n";

    }
}    
?>

Upvotes: 0

Views: 316

Answers (2)

Daniel Kucal
Daniel Kucal

Reputation: 9242

Try

if(!($line_num % 2)){
    // your code
}

Upvotes: 0

Barmar
Barmar

Reputation: 782025

Use the modulo operator on the line number. If it's 0 then the line is even, if it's 1 then the line is odd (these line numbers are zero-based -- swap them if you want one-based counting). Then use the continue statement to skip the rest of the loop body and go to the next line.

foreach ($lines as $line_num => $line) {
    if ($line_num % 2 == 1) {
        continue; // Skip odd lines
    }
    ...
}

Upvotes: 1

Related Questions