3

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?

8
  • 2
    Possible Duplicate: stackoverflow.com/questions/21172208/… Commented May 9, 2016 at 7:17
  • use http_build_query Commented May 9, 2016 at 7:18
  • 1
    http_build_query create this result : 0=1&1=2&2=3&3=4 but i want this result : arr[0]=1&arr[1]=2&arr[2]=3 Commented May 9, 2016 at 7:19
  • 2
    this will help: foreach ($arr as $key => $value) { $queryString[] = "arr[$key]=$value"; } echo implode("&",$queryString); Commented May 9, 2016 at 7:26
  • thank you... i use this now ... but i was Curious for a built in func in php Commented May 9, 2016 at 7:28

2 Answers 2

8

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

Sign up to request clarification or add additional context in comments.

Comments

0

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 :)

1 Comment

ahah, nice trick, btw a foreach loop will be more efficient on processing time :p

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.