note 101145 modified in function.array-replace by danbrown

From: Date: Mon, 29 Nov 2010 18:09:15 +0000
Subject: note 101145 modified in function.array-replace by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-174447@lists.php.net to get a copy of this message
I got hit with a noob mistake. :) When the function was called more than once, it threw a function redeclare error of course. The enviroment I was coding in never called it more than once but I caught it in testing and here is the fully working revision. A simple logical step was all that was needed. With PHP 5.3 still unstable for Debian Lenny at this time and not knowing if array_replace would work with multi-dimensional arrays, I wrote my own. Since this site has helped me so much, I felt the need to return the favor. :) <?php // Polecat's Multi-dimensional array_replace function // Will take all data in second array and apply to first array leaving any non-corresponding values untouched and intact function polecat_array_replace( array &$array1, array &$array2 ) { // This sub function is the iterator that will loop back on itself ad infinitum till it runs out of array dimensions if(!function_exists('tier_parse')){ function tier_parse(array &$t_array1, array&$t_array2) { foreach ($t_array2 as $k2 => $v2) { if (is_array($t_array2[$k2])) { tier_parse($t_array1[$k2], $t_array2[$k2]); } else { $t_array1[$k2] = $t_array2[$k2]; } } return $t_array1; } } foreach ($array2 as $key => $val) { if (is_array($array2[$key])) { tier_parse($array1[$key], $array2[$key]); } else { $array1[$key] = $array2[$key]; } } return $array1; } ?> --was-- I got hit with a noob mistake. :) When the function was called more than once, it threw a function redeclare error of course. The enviroment I was coding in never called it more than once but I caught it in testing and here is the fully working revision. A simple logical step was all that was needed. // Polecat's Multi-dimensional array_replace function // Will take all data in second array and apply to first array leaving any non-corresponding values untouched and intact function polecat_array_replace( array &$array1, array &$array2 ) { // This sub function is the iterator that will loop back on itself ad infinitum till it runs out of array dimensions if(!function_exists('tier_parse')){ function tier_parse(array &$t_array1, array&$t_array2) { foreach ($t_array2 as $k2 => $v2) { if (is_array($t_array2[$k2])) { tier_parse($t_array1[$k2], $t_array2[$k2]); } else { $t_array1[$k2] = $t_array2[$k2]; } } return $t_array1; } } foreach ($array2 as $key => $val) { if (is_array($array2[$key])) { tier_parse($array1[$key], $array2[$key]); } else { $array1[$key] = $array2[$key]; } } return $array1; } http://php.net/manual/en/function.array-replace.php

« previous php.notes (#174447) next »