[英]How to var_dump an iteration in php?
Usually I use var_dump with xDebug for debugging. 通常我使用var_dump和xDebug进行调试。 It's good for non-iteration.
这对于非迭代非常有用。 But for iteration, since I use die() to stop the script, then the result always comes up with the first iteration.
但是对于迭代,因为我使用die()来停止脚本,所以结果总是出现第一次迭代。 How can I var_dump the x iteration?
我怎样才能var_dump x迭代?
foreach ($files as $file) {
var_dump($file);die;
}
You can access a specific index of the array this way: 您可以通过以下方式访问数组的特定索引:
var_dump($files[0]); //first position
var_dump($files[1]); //second position and so on...
You can also use var_dump passing an array, it'll print the array's structure. 你也可以使用var_dump传递一个数组,它会打印数组的结构。
And you can just keep using var_dump as you already are, but put that die inside an if statement like this 你可以像现在一样继续使用var_dump,但是把它放在像这样的if语句中
foreach ($files as $key => $file) {
var_dump($file);
if ($key == count($files)-1) die; //it will die after the var_dump of the last element of the array
}
Food for thought, an alternate way: 思考的食物,另一种方式:
array_walk($files, function ($file, $i) {
var_dump($file);
($i == 1) && die;
// your code
});
I like to keep my debugging code compact as possible, because I write a lot of it that just gets thrown away. 我喜欢尽可能地保持我的调试代码紧凑,因为我写了很多它被扔掉了。
If you might want the debug code to hang around, consider a strategy pattern: 如果您可能希望调试代码闲置,请考虑策略模式:
$worker = function ($file, $i) {
// your code
};
$debugger = function ($file, $i) use ($worker) {
var_dump($file);
($i == 1) && die;
return $worker($file, $i);
};
$debugLevel = 1;
array_walk($files, (0 < $debugLevel ? $debugger : $worker));
If you have a debug level of 1 or more, the debugging function is called: it just does some diagnostics then passes to the worker. 如果调试级别为1或更高,则调用调试函数:它只是执行一些诊断,然后传递给worker。 Otherwise, the worker is called directly.
否则,直接调用该工作程序。
For the seventh iteration: 对于第七次迭代:
$i=1;
foreach($files as $file) {
if($i=7) { var_dump($file); die(); }
$i++;
}
But moving the die()
outside of the loop would give you all. 但是将
die()
移到循环之外会给你所有。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.