Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3

Thread: arrays

  1. #1
    New Coder
    Join Date
    Jul 2003
    Posts
    66
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Question arrays

    how come these line numbers appear? what exactly tell php to make'em?

    PHP Code:
    // 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";

    tnx!

  • #2
    Senior Coder
    Join Date
    Jun 2002
    Location
    frankfurt, german banana republic
    Posts
    1,848
    Thanks
    0
    Thanked 0 Times in 0 Posts
    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.
    De gustibus non est disputandum.

  • #3
    Regular Coder
    Join Date
    Jun 2002
    Location
    Sheffield, UK
    Posts
    552
    Thanks
    0
    Thanked 0 Times in 0 Posts
    correct me if i'm wrong, but that code appears to start at line 0, which will throw off any line number by 1....
    "To be successful in IT you don't need to know everything - just where to find it in under 30 seconds"

    (Me Me Me Me Me Me Me Me Me)


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •