Go Back   CodingForums.com > :: Server side development > PHP > Post a PHP snippet

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rating: Thread Rating: 2 votes, 5.00 average.
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 11-09-2005, 08:14 PM   PM User | #1
missing-score
Senior Coder


 
missing-score's Avatar
 
Join Date: Jan 2003
Location: UK
Posts: 2,194
Thanks: 0
Thanked 0 Times in 0 Posts
missing-score is on a distinguished road
Build Querystring from an array in PHP4 and 5

PHP5 has a great built in function to build a querystring from an array, called http_build_query ( http://www.php.net/http-build-query ), However this isn't available in PHP.

This function will build a query from any given array, just like the http_build_query function. If the function is available it will use the built in http_build_query, otherwise it will use its own method for making the query.

Simple to use, just call:

http_parse_query( $array )

PHP Code:
<?php
function http_parse_query$array NULL$convention '%s' ){
        
    if( 
count$array ) == ){
    
        return 
'';
        
    } else {
        
        if( 
function_exists'http_build_query' ) ){
        
            
$query http_build_query$array );
            
        } else {
            
            
$query '';
                
            foreach( 
$array as $key => $value ){
                
                if( 
is_array$value ) ){
                    
                    
$new_convention sprintf$convention$key ) . '[%s]';
                    
$query .= http_parse_query$value$new_convention );
                        
                } else {
                    
                    
$key urlencode$key );
                    
$value urlencode$value );
                        
                    
$query .= sprintf$convention$key ) . "=$value&";
                        
                }
                    
            }
                
        }
        
        return 
$query;
            
    }
        
}
?>
example usage:

PHP Code:
$values = array(
   
'act' => 'home',
   
'settings' => array(
      
'thread' => 20,
      
'post' => 10
   
)
);
$querystring http_parse_query$values );
$url 'mysite.com/index.php?' $querystring;
echo 
$url
outputs:

mysite.com/index.php?act=home&settings[thread]=20&settings[post]=10
missing-score is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 02:30 AM.


Advertisement
Log in to turn off these ads.