Welcome to WebmasterWorld Guest from

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

Array to string conversion



7:55 am on Feb 11, 2009 (gmt 0)

5+ Year Member

Hi all.

Okay, I've been struggling with this issue quite a bit. Let's say I have an array that I need to convert to a string, in order to post it off to some URL.

I know this is going to need to be accomplished using recursion, but for the life of me I don't know how to go about it :(

Here's an example of the input:

$arr[Profile][name] = 'my name';
$arr[Profile][surname] = 'surname';
$arr[Profile][item][0] = 'item 1';
$arr[Profile][item][1] = 'item 2';
$arr[Profile][item][2] = 'item 3';
$arr[foo][bar][foo1][bar2] = 'blerg';

And this is what it needs to look like (in order to do a normal POST, and it needs to be as a string):

data[Profile][name]=my name&data[Profile][surname]=surname&data[Profile][item][0]=item 1&data[Profile][item][1]=item 2&data[Profile][item][2]=item 3&data[foo][bar][foo1][bar2]=blerg

I hope this makes sense, and that there is someone that can help me. I'm at my wits' end as to how to accomplish this!



8:33 am on Feb 11, 2009 (gmt 0)

10+ Year Member

Try the following code but I haven't tested it

function a2s ($name, $var)
if (!is_array($var))
$s = "$name=$var";
$s = "";
foreach($var as $key => $value)
if ($s != "")
$s .= "&";
$s .= a2s("$name[$key]", $value);
return $s;

And call with

$str = a2s("data", $arr);


10:10 am on Feb 11, 2009 (gmt 0)

5+ Year Member

Thanks for the pointer, adb64. The code actually didn't work, but I managed to find another way of doing it :) I've posted the code below:

function data($data)
$data['Test']['test2']['test3'] = array(1,2,3,4,5,6,7,8,9,0);
$post = http_build_query($data, '', '<&>');
$post = str_replace(array('%5B', '%5D'), array('[', ']'), $post);
$post = preg_replace(array('#(\<&>\)([^[]*)#i', '#^([^[]*)#i'), array('&data[$2]', 'data[$1]'), $post);
return $post;

Might not be the most efficient of ways, but it works for what I need it for :)

Thanks for the help anyway.


2:05 pm on Feb 11, 2009 (gmt 0)

WebmasterWorld Administrator coopster is a WebmasterWorld Top Contributor of All Time 10+ Year Member

What do you need it for? POST data, as you first stated?

in order to post it off to some URL

If so, it is quite simple, just use the PHP built in function http_build_query [php.net]:

$post = http_build_query(array('data' => $arr));

I added the 'data' index for the entire array as that is what you seem to want.

Featured Threads

Hot Threads This Week

Hot Threads This Month