note 57480 deleted from function.http-build-query by hholzgra

From: Date: Thu, 02 Aug 2012 13:36:12 +0000
Subject: note 57480 deleted from function.http-build-query by hholzgra
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-189770@lists.php.net to get a copy of this message
Note Submitter: vlad_mustafin at ukr dot net ---- Dear anonymous, i think that your example is incorrect in some places (or at least is not flexible) and shortly only in names of variables (as $c, $k, etc.) and some spaces and line foldings :), i can explain: 1. I think that next part of code is not wanted here: <?if (!is_array($a)) return false;?> because you have (array)$a in foreach! It is possible but not obligatory. Or maybe better to use trigger_error for this situation. 2. You don't use urlencode on key! It's wrong because it can have also unsafe value! <?if ($c) $k=$b."[".$k."]"; elseif (is_int($k)) $k=$b.$k;?> this part is wrong because $k can be integer even if $c is not empty. I can want to add numeric_prefix to all indexes in array, but your example will not allow to make it. Here using of elseif is excluded, these both conditions should exist simultaneously. 3. <?http_build_query($v,$k,1);?> - In my opinion it's a very rough error. You use second parameter (as "numeric_prefix" in my example and php manual for this function) for transfer of the current key into next iteration step of recursion. Certainly it's possible and is not of principle, but very not professionally, in my opinion. I use implicit rule: one ought not to violate function logic even inside of the same function one may only expand logic. And my <?http_build_query($v, null, $tmp_key);?> allows to add numeric_prefix to all indexes in array (see point 2), i need just to put $numeric_prefix instead of null into second parameter. Also i want to extend my previous example because we must use ini_get('arg_separator.output') instead of '&' separator! <? if(!function_exists('http_build_query')) { function http_build_query( $formdata, $numeric_prefix = null, $key = null ) { $res = array(); foreach ((array)$formdata as $k=>$v) { $tmp_key = urlencode(is_int($k) ? $numeric_prefix.$k : $k); if ($key) $tmp_key = $key.'['.$tmp_key.']'; if ( is_array($v) || is_object($v) ) { $res[] = http_build_query($v, null /* or $numeric_prefix if you want to add numeric_prefix to all indexes in array*/, $tmp_key); } else { $res[] = $tmp_key."=".urlencode($v); } /* If you want, you can write this as one string: $res[] = ( ( is_array($v) || is_object($v) ) ? http_build_query($v, null, $tmp_key) : $tmp_key."=".urlencode($v) ); */ } $separator = ini_get('arg_separator.output'); return implode($separator, $res); } } ?> All best!

« previous php.notes (#189770) next »