Search code examples
phpforeachphpstormxdebugbreak

How to break foreach loop from a XDebug session?


I have a foreach loop and that is doing some time consuming stuff:

$someHugeArray = [...]; // having beyond 300 to 1000 items

foreach ($someHugeArray as $item) {
    $this->applyTimeConsumingMagic($item);
}

When debugging this I try to avoid iterating all of them items, so I am often writing escape code along the lines of:

foreach ($someHugeArray as $i => $item) {
    $this->applyTimeConsumingMagic($item);

    if ($i > 10) { break; } // @fixme: should not go live
}

And as the comment indicates, something like this did once go live making me feel like an amateur.

Is there some way to break the foreach loop from an XDebug session without writing var_dumpy code? As an IDE I use PhpStorm.


Solution

  • I did not find a way to break a foreach loop on the fly, yet the best next thing one can do is to decrease the array size on the fly.

    • Set a breakpoint after you set up your array, at best before the loop starts. (It does work inside the loop as well, yet could have weird behavior)
    • Select Evaluate expression phpstorm's debug window or use shortcut, default should be Alt + Shift + 8
    • run $someHugeArray = array_slice($someHugeArray, $offset = 0, $length = 10);

    Besides array_slice one could also use array_filter if one wants to filter by more specific conditions using a closure.

    Now you have a small array, enjoy fast execution time without having to worry to clean up after your debug session.