简体   繁体   中英

How to var_dump an iteration in php?

Usually I use var_dump with xDebug for debugging. 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. How can I var_dump the x iteration?

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.

And you can just keep using var_dump as you already are, but put that die inside an if statement like this

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM