1

I have following example PHP code and its working great! but i just want one more addition so it print line number too.

<?php
$path = shell_exec('cat data.txt');
$path = chop($path,"\n");
$lines =  explode("\n",$path);
echo "<h2><a href=\"http:\"\" title=\"Summery\">List of Studies</a></h2>";

foreach($lines as $line) {
        echo "<h3><p>$line</p></h3>";
}
        ?>

Output:

ABC
XYZ
123

I want following addition and add counter in it.

1. ABC
2. XYZ
3. 123
1
  • Have you considered using the file function? It will automatically split lines for you Commented Jun 5, 2013 at 20:18

5 Answers 5

5

You can assign the index to variable too, not just the value:

foreach($lines as $index => $line) {
    printf('<h3><p>%d. %s</p></h3>', $index + 1, $line);
}
Sign up to request clarification or add additional context in comments.

5 Comments

The counter will start at 0 for this code. You could make it start at 1 with {$index+1} in place of {$index}
Good point, but I don't think {$index+1} would work inside a string
You example is super simple but only problem is it first counter is 0 :(
Holy smoke!!! you guys are freaking awesome! printf('<h3><p>%d. %s</p></h3>', $index + 1, $line); did magic :)
@Satish If you do not use the <ol> tag answer, you sir are a fool!
3

If you don't want to use the index php, you can use the tag ol

Reff: http://www.w3schools.com/tags/tryit.asp?filename=tryhtml_lists

5 Comments

This has to be the accepted answer!!!! By far the most obvious answer. How could someone >2k rep even be asking this 0_o
thank you! , Sometimes it is inevitable to use the index, but in this case, it is trivial to use
@lan - I am not a php developer, I am Linux admin, and i just came across with this issue and pop up question. I know you are freaking genius then what the hell you doing here...
In my example its not going to work because i am not playing with index its a loop. I don't know why bit its not doing what i want.. sorry
All questions are important! in your case using the ol tag would solve your problem and save 0.0011 of its processing
2
$i=1;
foreach($lines as $line) {
    echo "<h3><p>$i. $line</p></h3>";
$i++;
}

1 Comment

You example is perfectly fit in my Senior
2
<?php
$path = shell_exec('cat data.txt');
$path = chop($path,"\n");
$lines =  explode("\n",$path);
echo "<h2><a href=\"http:\"\" title=\"Summery\">List of Studies</a></h2>";
$c = 0;
foreach($lines as $line) {
        $c++
        echo "<h3><p>".$c.". ".$line."</p></h3>";
}
?>

Comments

1

http://www.php.net/manual/en/control-structures.foreach.php

foreach($lines as $i=>$line) {
        echo "<h3>$i. <p>$line</p></h3>";
}

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.