long
long

Reputation: 218

Ignore the first n elements of array in foreach($array as $element)

Part A: Generically, is there a simple way to ignore the first n elements of an array when running a foreach ($array as $element)?

Part B: Specifically, the application is in a backtrace function I use, where I know that the first two elements are always trivial, and so I wish to exclude them from output. I know it is possible to limit the number of stack frames returned, but it's the first couple that I want to ignore. I know I can do this using a loop counter or similar, but wondered whether there may be a more 'elegant' solution.

$array = debug_backtrace();
foreach ($array as $element) // but ignore the first two 
{
  $backtrace.="\n > ".$element['function']." -> line ".$element['line']." in ".$element['file'];
}

Upvotes: 1

Views: 980

Answers (1)

Guillaume Lhz
Guillaume Lhz

Reputation: 904

use array slice :

$array = debug_backtrace();
$output = array_slice($array , 2); 
foreach ($output as $element) // but ignore the first two 
{
  $backtrace.="\n > ".$element['function']." -> line ".$element['line']." in ".$element['file'];
}

Upvotes: 4

Related Questions