duandaoji3992 2016-06-13 00:48
浏览 84
已采纳

打印数组时,如何删除恼人的“数组()”

Currently, I have an array, but when I print it using print_r it comes out something like:

Array (

[0] mouse

[1] cat

[2] dog

}

My question is, is it possible to ONLY print out the array contents, and not the "Array ( )" in there?

</div>
  • 写回答

2条回答 默认 最新

  • douwen1901 2016-06-13 00:55
    关注

    There are various ways like this:

    Simple foreach

    $arr = ['mouse', 'cat', 'dog'];
    
    foreach ($arr as $key => $value) {
        echo "[$key] $value<br/>";
    }
    

    Using array_walk:

    array_walk($arr,function($value,$key){
        echo "[$key] $value<br/>";
    });
    

    Result:

    [0] mouse
    [1] cat
    [2] dog
    

    Incase you needn't any index, just want to print the values:

    foreach ($arr as $value) {
        echo "$value<br/>";
    }
    

    Using array_map

    array_map(function($value){
        echo "$value<br/>";
    }, $arr);
    

    Results:

    mouse
    cat
    dog
    

    You can use implode to join the array values and print as a string:

    echo implode(",", $arr);
    

    You can also use join which is alias of implode:

    echo join(",", $arr);
    

    prints:

    mouse,cat,dog
    

    You can also use json_encode format to convert your array to JSON

    echo json_encode($arr);
    

    prints:

    ["mouse","cat","dog"]
    

    (credits: @here2Help)

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

报告相同问题?