From array to URL
$_GET is an associative array of variables passed in URL.
Example:
http://exemplo.com?name=Alejandro&age=23&gender=male
That URL have many variables:
print_r($_GET); array ( name => Alejandro, age => 23, gender => male )
We can access the variable values using indexes:
echo $_GET['age']; // show 23 echo $_GET['gender']; // show male
From array to URL parameters
Doesn’t exists an native PHP function to convert array in URL parameters. So lets make our function:
function arrtourl($arr, $entity=true, $prefix='') {
$params = array();
foreach ($arr as $k => $v)
if ($v)
$params[] = is_array($v) ? arrtourl($v, $entity, $prefix ? $prefix.'['.$k.']' : $k) : sprintf($prefix ? $prefix.'[%s]' : '%s', urlencode($k)).'='.urlencode($v);
return implode($entity ? '&' : '&', $params);
}
Parameters
$arr- is the array to be converted.
$entity- is a boolean who defines if the parameters will be joined using & or &. The default value is true because in most cases the URL parameters create from here will be used in HTML content.
$prefix- this parameters are used in recursions when
$arris an matrix.
Examples
Simple:
$arr = array( 'id' => 968, 'cat' => 'php' ); echo arrtourl($arr); >> id=968&cat=php
Matrix:
$mat = array( 'test' => array( 'id' => 968, 'cat' => php ), 'status' => 1, 'seq' => array( 1, 2, 3 ) ); echo arrtourl($mat); >> test[id]=968&test[cat]=php&status=1&seq[0]=1&seq[1]=2&seq[2]=3
Many dimensions:
$arr = array( 'val' => array( array( array( 'test' ) ) ) ); echo arrtourl($arr); >> val[0][0][0]=test
Just &:
$arr = array(
'id' => 968,
'cat' => 'php',
);
// id=968&cat=php
$url = arrtourl($arr, false);
header('Location: mypage?'.$url);
Adding prefix:
$arr = array( 'id' => 968, 'cat' => 'php' ); echo arrtourl($arr, false, 'post'); >> post[id]=968&post[cat]=php