Navid_pdp11
Navid_pdp11

Reputation: 4032

how to serialize array as url queryString in php?

I need to convert an array such as this:

$arr = array(1, 2, 3) ; 

to this format:

arr[0]=1&arr[1]=2&arr[2]=3

is there any built in function in php or i must create this my self?

Upvotes: 3

Views: 4926

Answers (2)

Girish
Girish

Reputation: 12127

expected output should require key name in input data array, see below and after that use http_build_query() function to created query string

<?php 
$arr = array("arr" => array(1, 2, 3)) ; 
echo http_build_query($arr);
?>

encode output default

arr%5B0%5D=1&arr%5B1%5D=2&arr%5B2%5D=3

and if you need decode output then

<?php 
$arr = array("arr" => array(1, 2, 3)) ; 
echo urldecode(http_build_query($arr));
?>

arr[0]=1&arr[1]=2&arr[2]=3

Upvotes: 8

Thamilhan
Thamilhan

Reputation: 13313

You can use http_build_query but with little tweak:

<?php 
$arr = array(1, 2, 3); 
$arr = http_build_query($arr,"arr[");
echo preg_replace('/\[\d/', '\\0]', $arr);

Output:

arr[0]=1&arr[1]=2&arr[2]=3

here is demo

Alternatively, you can also use:

<?php 
$arr = array(1, 2, 3);
foreach ($arr as $key => $value) { 
  $serialized[] = "arr[$key]=$value"; 
} 
echo implode("&",$serialized);

As mentioned by @Bob0t in comments, he says its faster :)

Upvotes: 0

Related Questions