View Full Version : arrays

11-11-2003, 10:17 PM
how come these line numbers appear? what exactly tell php to make'em?

// Get a file into an array. In this example we'll go through HTTP to get
// the HTML source of a URL.
$lines = file ('http://www.example.com/');

// Loop through our array, show html source as html source; and line numbers too.
foreach ($lines as $line_num => $line) {
echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br>\n";


11-12-2003, 12:56 AM
It's just the way the foreach loop works with sequential arrays. On each iteration, the key of the current key-value pair is mapped to $line_num, whereas the value (the line itself) is in $line.

So what are the keys of a sequential array (i.e. an array only with numerical indices, like $file[0], $file[1],... in our examle)?
Answer: The numerical index is the key. And just looking at the syntax makes it clear that it carries some sense with it, because you use either a string as a key to get at a field, or a number.

That's why using a foreach loop with numerical indices "works" in your example, and it can be applied to other code problems in PHP too.

11-16-2003, 11:51 AM
correct me if i'm wrong, but that code appears to start at line 0, which will throw off any line number by 1....

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum