Return to Snippet

Revision: 40071
at January 25, 2011 22:07 by jli


Initial Code
<?php
function encode_array($args)
{
  if(!is_array($args)) return false;
  $c = 0;
  $out = '';
  foreach($args as $name => $value)
  {
    if($c++ != 0) $out .= '&';
    $out .= urlencode("$name").'=';
    if(is_array($value))
    {
      $out .= urlencode(serialize($value));
    }else{
      $out .= urlencode("$value");
    }
  }
  return $out . "\n";
}
?>

If there are arrays within the $args array, they will be serialized before being urlencoded.

Some examples:
<?php
echo encode_array(array('foo' => 'bar'));                    // foo=bar
echo encode_array(array('foo&bar' => 'some=weird/value'));   // foo%26bar=some%3Dweird%2Fvalue
echo encode_array(array('foo' => 1, 'bar' =>  'two'));       // foo=1&bar=two
echo encode_array(array('args' => array('key' => 'value'))); // args=a%3A1%3A%7Bs%3A3%3A%22key%22%3Bs%3A5%3A%22value%22%3B%7D
?>

Initial URL
http://www.php.net/manual/en/function.urlencode.php#97191

Initial Description
This code comes from the php documentation (see url)

Initial Title
Pass array to url

Initial Tags
url, array

Initial Language
PHP