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条)

报告相同问题?

悬赏问题

  • ¥60 pb数据库修改或者求完整pb库存系统,需为pb自带数据库
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路