3 ms·
> But this is bad, really bad idea. This is bad code, it doesn't describe what you want to achieve, it's difficult to track and analyze, it's hard to tell when
by pbowyer 12y ago
> But this is bad, really bad idea. This is bad code, it doesn't describe what you want to achieve, it's difficult to track and analyze, it's hard to tell when it stops. You really should want recursion here.
Thanks for the warning :) It felt much cleaner, my code for the one like above:
$documents = $start_ids;
foreach ($documents as $id) {
$sub_ids = getChildren($id, 1);
// Now filter out any which appear in $stop_ids
$sub_ids = array_diff($sub_ids, $stop_ids);
$documents = array_merge($documents, $sub_ids);
}
print_r($documents);
And the one with recursion:
$documents = $start_ids;
foreach ($start_ids as $id) {
recurse($id, $documents);
}
print_r($documents);
function recurse($id, &$documents)
{
global $stop_ids;
$sub_ids = getChildren($id);
// Now filter out any which appear in $stop_ids
$sub_ids = array_diff($sub_ids, $stop_ids);
$documents = array_merge($documents, $sub_ids);
foreach ($sub_ids as $sid) {
recurse($sid, $documents);
}
}
> And it's not "pass by reference" here. References have nothing to do.
I've seen this terminology used in PHP - describing 'foreach' as "pass by copy" to make it clear that you can alter the argument and it won't affect the loop, as a copy was made when foreach was run. How would you describe it instead?