Professional Web Applications Themes

While loop in array does not start with first entry - PHP Development

Help! I am using arrays and a while loop for go through all the elements. The problem is that the first element is missing: while ($val = next($array)) { $key = key($array); echo "$key: $val\n" }...

  1. #1

    Default While loop in array does not start with first entry

    Help!

    I am using arrays and a while loop for go through all the elements. The
    problem is that the first element is missing:

    while ($val = next($array))
    {
    $key = key($array);
    echo "$key: $val\n"

    }
    Matthias Guest

  2. #2

    Default Re: While loop in array does not start with first entry

    Matthias Braun said the following on 05/06/2005 18:51: 

    reset($array);


    --
    Oli
    Oli Guest

  3. #3

    Default Re: While loop in array does not start with first entry

    I noticed that Message-ID:
    <42a33bbd$0$14739$arcor-online.net> from Matthias
    Braun contained the following:
     

    That's what foreach is for

    foreach ($array as $key => $value) {
    echo "Key: $key; Value: $value<br />\n";
    }


    --
    Geoff Berrow 0110001001101100010000000110
    001101101011011001000110111101100111001011
    100110001101101111001011100111010101101011
    Geoff Guest

  4. #4

    Default Re: While loop in array does not start with first entry

    Matthias Braun wrote: 

    next() will always get the next element by moving the pointer ahead. To get
    the first element, use current():

    $val = current($array);
    while ($val !== false) {
    $key = key($array);
    echo "$key: $val\n";
    $val = next($array);
    }

    Or use list() with each():

    while (list($key, $val) = each($array)) {
    echo "$key: $val\n";
    }

    Or even better, use foreach as Geoff mentioned.


    JW



    Janwillem Guest

Similar Threads

  1. loop through array to build a new array
    By pope on acid in forum Macromedia Flex General Discussion
    Replies: 0
    Last Post: April 22nd, 11:18 AM
  2. array data matches but array created in loop doesn't work
    By Reed Law in forum PHP Development
    Replies: 1
    Last Post: August 13th, 04:25 AM

Bookmarks

Posting Permissions

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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139