How to get the current recursion level in a PHP function

How to get the current recursion level in a PHP function? I mean, is there any β€œmagic” (or, ultimately, normal) function:

function doSomething($things) { if (is_array($things)) { foreach ($things as $thing) { doSomething($thing); } } else { // This is what I want : echo current_recursion_level(); } } 

I know that I can use another function argument ( $level in this example):

 function doSomething($things, $level = 0) { if (is_array($things)) { foreach ($things as $thing) { $level++; doSomething($thing, $level); } } else { echo $level; } } 

But I want to know if there is a built-in function (or trick) for this. Maybe something with debug_backtrace() , but it doesn't seem like a simple or quick solution.

I did not find this information, perhaps it simply does not exist ...

+6
source share
4 answers

If you just want to avoid a hit on recursion level 100 PHP,

 count(debug_backtrace()); 

should be enough. Otherwise, you have no choice to pass a depth argument, although the precrement statement makes it somewhat cleaner, as shown in the example below.

 function recursable ( $depth = 0 ) { if ($depth > 3) { debug_print_backtrace(); return true; } else { return recursable( ++$depth ); } } 
+7
source

You need to figure it out on your own, the only alternative could be something like XDebug, which profiles your complete software. But it is very inefficient.

 <?php function my_recursive_fn($param) { static $counter = 0; if (is_array($param)) { ++$counter; foreach ($param as $k => $v) { } } else { echo $counter; --$counter; // If we're returning (only PHP 5.5+) try { return $counter; } finally { --$counter; } } } ?> 

This allows you to calculate without a second public parameter.

+1
source
  function doSomething($things) { static $level = 0; if (is_array($things)) { foreach ($things as $thing) { $level++; doSomething($thing); } } else { // This is what I want : echo $level } } 
0
source

In java you can check the call stack. I think you can do the same in php:

debug-backtrace Is this the one you are looking for?

Since php does not optimize recursion with tail calls, this should indicate the depth of the recursion.

0
source

Source: https://habr.com/ru/post/957894/


All Articles