druzuz321103 2013-03-05 21:58 采纳率: 100%
浏览 182
已采纳

使用for循环打印数组

I want to print this array to all indexes upto 21, but in this code this is printing only to array length, what i should i do the print whole array in for loop?

<?php
$array=array(0=>"hello",
             1=>"world", 
             2=>"this", 
             3=>"is", 
             4=>"an", 
             20=>"array",
             21=>"code" );

$length=count($array);

for($i=0;$i<$length;$i++){
         echo "$i=>".$array[$i]; 
         echo "<br />";

      }
?>
  • 写回答

4条回答 默认 最新

  • dongzha2525 2013-03-05 22:12
    关注

    Your difficulty is the way you're defining your array:

    $array=array(0=>"hello",
                 1=>"world", 
                 2=>"this", 
                 3=>"is", 
                 4=>"an", 
                 20=>"array",
                 21=>"code" );
    

    Arrays in php are really hashmaps; when you call index 5 on the above array, it is undefined. No index item up to 20 will be defined, and these will Notice out:

    PHP Notice:  Undefined offset:  5
    

    Because you're using array length as your iterating variable, and calling exactly that variable, you will never get positions 20 and 21 in your code.

    This is what your array looks like to the computer:

    0 => "hello"
    1 => "world"
    2 => "this"
    3 => "is"
    4 => "an"
    5 => NULL
    6 => NULL
    7 => NULL
    ... //elided for succinctness 
    19 => NULL
    20 => "array"
    21 => "code"
    

    When you call $array[7] it can't return anything. When you call $array[20] it will return "array".

    What you really want is a foreach loop:

    foreach($array as $key => $val) {
        //key will be one of { 0..4, 20..21}
        echo "$key is $value
    ";
    }
    

    Resulting in:

    $ php test.php 
    0 is hello
    1 is world
    2 is this
    3 is is
    4 is an
    20 is array
    21 is code
    

    If you must use a for loop:

    $key_array = array_keys($array);
    for($i=0;$i<count($key_array);$i++){
       $key = $key_array[$i];
       echo "$key => ".$array[$key]."
    ";
    }
    

    Note this is not a clean solution.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?