使用循环打印 PHP 数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1293896/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP array printing using a loop
提问by user156073
If I know the length of an array, how do I print each of its values in a loop?
如果我知道数组的长度,如何在循环中打印它的每个值?
回答by Sampson
$array = array("Jonathan","Sampson");
foreach($array as $value) {
print $value;
}
or
或者
$length = count($array);
for ($i = 0; $i < $length; $i++) {
print $array[$i];
}
回答by Pim Jager
Use a foreach loop, it loops through all the key=>value pairs:
使用 foreach 循环,它循环遍历所有的 key=>value 对:
foreach($array as $key=>$value){
print "$key holds $value\n";
}
Or to answer your question completely:
或者完全回答你的问题:
foreach($array as $value){
print $value."\n";
}
回答by code.rider
for using both things variables value and kye
用于同时使用变量 value 和 kye
foreach($array as $key=>$value){
print "$key holds $value\n";
}
for using variables value only
仅用于使用变量值
foreach($array as $value){
print $value."\n";
}
if you want to do something repeatedly until equal the length of array us this
如果你想重复做一些事情直到等于数组的长度我们这个
// for loop
for($i = 0; $i < count($array); $i++) {
// do something with $array[$i]
}
Thanks!
谢谢!
回答by GYANENDRA PRASAD PANIGRAHI
Here is example:
这是示例:
$array = array("Jon","Smith");
foreach($array as $value) {
echo $value;
}
回答by Zed
foreach($array as $key => $value) echo $key, ' => ', $value;
回答by Jakub
I also find that using <pre></pre>tags around your var_dump or print_r results in a much more readable dump.
我还发现<pre></pre>在 var_dump 或 print_r 周围使用标签会导致更易读的转储。
回答by knittl
either foreach:
要么 foreach:
foreach($array as $key => $value) {
// do something with $key and $value
}
or with for:
或用于:
for($i = 0, $l = count($array); $i < $l; ++$i) {
// do something with $array[$i]
}
obviously you can only access the keys when using a foreach loop.
显然,您只能在使用 foreach 循环时访问密钥。
if you want to print the array (keys and) values just for debugging use var_dumpor print_r
如果您只想打印数组(键和)值以供调试使用var_dump或print_r
回答by Freeman
Another advanced method is called an ArrayIterator. It's part of a wider classthat exposes many accessible variablesand functions. You are more likely to see this as part of PHPclasses and heavily object-orientedprojects.
另一种高级方法称为ArrayIterator. 它是一个更广泛的一部分,class它公开了许多可访问的variables和functions. 您更有可能将其视为PHP课程和重要object-oriented项目的一部分。
$fnames = ["Muhammed", "Ali", "Fatimah", "Hasan", "Hussein"];
$arrObject = new ArrayObject($fnames);
$arrayIterator = $arrObject->getIterator();
while( $arrayIterator->valid() ){
echo $arrayIterator->current() . "<br />";
$arrayIterator->next();
}
回答by Tom Ritter
If you're debugging something and just want to see what's in there for yourthe print_f functionformats the output nicely.
如果您正在调试某些内容并且只想查看您的 print_f 函数中的内容,则可以很好地格式化输出。

