a very simple questions about array

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • wesley1970
    New Member
    • Nov 2007
    • 15

    a very simple questions about array

    for example, we can make an array simply by the below method
    [code=php]
    <?php
    $var1 = a;
    $var2 = b;
    $var3 = c;
    $variables = array($var1,$va r2,$var3);
    ?>
    [/code]

    Below, we can use "for loop" to echo out 0,1,2,3,4....20 ,
    However, how can we use the "echo-out(0,1,2,3,4.. ..)" to make an array
    like the above one???
    [code=php]
    <?php
    for ($i=0; $i< 20; $i = $i + 1){ echo $i.",";}
    ?>
    [/code]
    Last edited by ak1dnar; Nov 7 '07, 04:41 PM. Reason: Fixed [CODE=php] Tags
  • r035198x
    MVP
    • Sep 2006
    • 13225

    #2
    Originally posted by wesley1970
    for example, we can make an array simply by the below method
    <?php
    $var1 = a;
    $var2 = b;
    $var3 = c;
    $variables = array($var1,$va r2,$var3);
    ?>


    Below, we can use "for loop" to echo out 0,1,2,3,4....20 ,
    However, how can we use the "echo-out(0,1,2,3,4.. ..)" to make an array
    like the above one???
    <?php
    for ($i=0; $i< 20; $i = $i + 1){ echo $i.",";}
    ?>
    1.) Use code tags when posting code
    2.) Always refuse to write a single line of code if you don't have the manual pages with you.

    Comment

    • adamalton
      New Member
      • Feb 2007
      • 93

      #3
      I'm not sure that I entirely understand what you're trying to do, but I think you might be after this:

      Make an array[PHP]$my_array=array ('cheese','carr ots','peanuts') ;[/PHP]
      Then print each item:[PHP]$number_of_item s=count($my_arr ay);
      for($i=0; $i<$number_of_i tems; $i++)
      {
      echo $my_array[$i];
      }[/PHP]

      You could just do:[PHP]foreach($my_arr ay as $item)
      {
      echo $item;
      }[/PHP]
      It saves having to count() the number of elements first.
      I hope that helps

      Comment

      • pbmods
        Recognized Expert Expert
        • Apr 2007
        • 5821

        #4
        To add to Adam's post:

        for is never the appropriate choice when you want to iterate through each element in an array; that's exactly why foreach was invented.

        With a foreach loop, each element gets assigned to a variable. In a for loop, however, PHP has to look up two variables and an array index. Very slow.

        Get in the habit of using foreach to iterate through arrays, and you will notice a dramatic speed increase (I've seen applications go from 1.5 seconds per page load down to 0.03 seconds per page load, and 0.8 seconds worth of that was from switching to foreach loops).

        (if you were curious, the remaining 0.67 seconds was saved by optimizing MySQL queries)

        Comment

        Working...