I just want to make sure I do it right and this will not create any conficts.
I have a function which calls itself and need your approval if it's OK or not to do so?
<?php
function determine($the_array){
foreach ($the_array as $key => $value) {
switch ($key) {
case 'in':
echo $value;
break;
case 'out':
echo $value;
break;
case 'level':
echo '<ul>';
determine($value);
echo '</ul>';
break;
}
}
}
This is the array:
$the_array = array(
'in' => '<li>Simple IN</li>',
'out' => '<li>Simple OUT</li>',
'level' => array(
'in' => '<li>Simple IN 2</li>',
'out' => '<li>Simple OUT 2</li>',
'level' => array(
'in' => '<li>Simple IN 3</li>',
'out' => '<li>Simple OUT 3</li>'
),
),
);
And here is the final init:
echo '<ul>';
determine($the_array);
echo '</ul>';
The result is just how I wanted to be, it works great, but I don't know if this is a good practice.
PHP is perfectly capable of having a function call itself.
A recursive function is a function that calls itself during its execution. The process may repeat several times, outputting the result and the end of each iteration.
Recursive function: Call php function itself.
Recursive functions are OK - but dangerous if you aren't sure you know what you are doing. If there is any chance that a function will end up in a recursive loop (where it keeps calling itself over and over) you will either time out, run out of memory or cause a zombie apocalypse.
Think of recursive calls as a really, really sharp knife - in the hands of an experienced chef, it's a match made in heaven, in the hands of the dishwasher, it is a lost finger waiting to happen.
PHP tries to play nice, and limits a recursive depth to 100 by default (though this can be changed) but for almost all cases, if your recursive depth gets to 100, the accident has already happened and PHP reacts by stopping any additional pedestrians from wandering into traffic. :)
Fluffeh provided sufficient answer as far as recursive functions are concerned. But when using recursion with large arrays/objects/etc, you should watch optimisation of your code, so that it doesn't take much memory or CPU power to execute.
You could easily optimise your code to be cleaner, take less memory and be more resilient to unexpected data. Notice the & in the function arguments list (it eliminates creating a copy of an array everytime a nested function is called).
function determine(& $the_array){
foreach ($the_array as $key => $value) {
switch ($key) {
case 'in':
case 'out':
echo $value;
break;
case 'level':
if (!is_array($value)) break;
echo '<ul>';
determine($value);
echo '</ul>';
break;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With