Hi, can someone please help me improve this function i wrote to display the contents of an array without using print_r function printarray($arr) { foreach ($arr as $key => $value) { if($value !== "" && $value !== " " && !empty($value) && isset($value)) { if(gettype($value) == 'array') {echo "$key: "; $this->printarray($arr[$key]);} else{echo "$key => $value<br />\n";} } } }
I would use a for loop instead of foreach. I will also just trim the value and check if it is empty or not, instead of doing 2 function calls and two checks. Lastly, I might also use is_array instead of gettype.
Thanks, ThePHPMaster, but i don't think you can access the keys and values of array with for like you can with foreach. I've take your advice for the is_array and to trim it. The function now as it stand is: function printarray($arr) { foreach ($arr as $key => $value) { if($value !== "" && $value !== " " && !empty(trim($value)) && isset($value)) { if(is_array($value)) {echo "$key: "; $this->printarray($arr[$key]);} else{echo "$key => $value<br />\n";} } } } Any other suggestions please?
Here is my final take. function printarray($arr) { $count = count($arr); $keys = array_keys($arr); for($x=0;$x<$count;$x++) { $key = $keys[$x]; $value = trim($arr[$key]); if(strlen($value) > 0) { if(is_array($arr[$key])) { echo "$key: "; printarray($arr[$key]); echo "<br />\n"; } else{ echo "$key => $value<br />\n"; } } } } PHP:
As am I, in this instance a foreach is completely appropriate, not only will it loop thru the correct amount, but has a way of retrieving the key without having to use a separate function. In PHP5, foreach can even iterate objects and not just arrays.
I stand corrected. Normally, the foreach statement is the best construct for iterating through an array. However, if we are modifying the elements in the array, foreach works on a copy of the array and would result in added overhead. Since we are not modifying the array, foreach would just work as good as the for loop.
Actually, foreach in PHP5 allows you to modify array values as well: foreach ($values as &$value) { $value += 1; } PHP:
You will find it on Question #10 Answer - Page 23 of "The Zend PHP Certification Practice Test Book" First Edition Jan 2005. You can also find it on Page 58 in "Zend PHP 5 Certification Study Guide".