note 105354 added to function.create-function

From: Date: Thu, 11 Aug 2011 05:14:15 +0000
Subject: note 105354 added to function.create-function
Groups: php.notes 
Request: Send a blank email to php-notes+get-182418@lists.php.net to get a copy of this message
phenno7 [a_t] yahoo dot com's example code makes effectively no use of create_function: one clear indication of this is that the body of the function is a single string literal without any part of it being constructed at runtime. It could just as easily have been written as: <?php $ctg_tree = array( '1'=>array('parent_id'=>0, 'children'=>array( '2'=>array('parent_id'=>1, 'children'=>array( '3'=>array('parent_id'=>2))), '4'=>array('parent_id'=>1, 'children'=>array( '5'=>array('parent_id'=>4), '6'=>array('parent_id'=>4)))))); function getBranchIds($tree, $ctg_id, $level = null, $arr = null, $push = false) { if(!$arr) { $arr = array(); } if(intval($level) && $push) { $level--; } $start = false; foreach($tree as $key=>$ctg) { if($push) { $arr[] = $key; } if($ctg_id == $key) { $start = true; $push = true; } if(!empty($ctg['children']) && (intval($level) || $level === null)) { $arr = getBranchIds($ctg['children'], $ctg_id, $level, $arr, $push); } if($start) { return $arr; } } return $arr; } function getSubCategories($ctg_tree, $id, $level = null) { return getBranchIds($ctg_tree, $id, $level, null, false); } print_r(getSubCategories($ctg_tree, 1, 2)); ?> And would almost surely be faster (I also made some tweaks to avoid messages about uninitialised variables and deprecated constructs). Which is not to say it could not be simplified: <?php function getBranchIds($tree, $level = null) { $arr = array(); if($level !== 0) { if(isset($tree['children'])) { foreach($tree['children'] as $key => $child) { $arr[] = $key; $arr = array_merge($arr, getBranchIds($child, $level - 1)); } } } return $arr; } function getSubCategories($ctg_tree, $id, $level = null) { if(isset($ctg_tree[$id])) { return getBranchIds($ctg_tree[$id], $level); } else { foreach($ctg_tree as $key => $ctg) { $arr = getSubCategories($ctg, $id, $level); if(!empty($arr)) { return $arr; } } return array(); } } ?> ---- Server IP: 69.147.83.197 Probable Submitter: 219.88.69.196 ---- Manual Page -- http://www.php.net/manual/en/function.create-function.php Edit -- https://master.php.net/note/edit/105354 Del: integrated -- https://master.php.net/note/delete/105354/integrated Del: useless -- https://master.php.net/note/delete/105354/useless Del: bad code -- https://master.php.net/note/delete/105354/bad+code Del: spam -- https://master.php.net/note/delete/105354/spam Del: non-english -- https://master.php.net/note/delete/105354/non-english Del: in docs -- https://master.php.net/note/delete/105354/in+docs Del: other reasons-- https://master.php.net/note/delete/105354 Reject -- https://master.php.net/note/reject/105354 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#182418) next »