How to urlencode a multidimensional array?


I have searched hi and low for a solution. I have a dynamic multidimensional array I need to break up and urlencode. The number of items will change but they will always have the same keys.

$formFields = Array ( 
[0] => Array ( [form_name] => productID [form_value] => 13 ) 
[1] => Array ( [form_name] => campaign [form_value] => [email protected] ) 
[2] => Array ( [form_name] => redirect [form_value] => ) ) 

Each array has a Form Name and a Form Value.

This is what I’m trying to get to:

$desired_results = 
productID => 13
campaign => [email protected]
redirect =>

Every time I try and split them up I end up with: form_name => productID or something like that.

I’m trying to take the results and then urlencode them:



This will return the values regardless of the names of the keys.

$result = array();

foreach ($formFields as $key => $value)
  $tmp = array_values($value);
  $result[$tmp[0]] = $tmp[1];

The foreach loops through the main array, storing the subarrrays in the variable $value. The function array_values return all the values from each array as a new numeric array. The value of [form_name] will be stored in the first index, [form_value] in the second.

The built in http_build_query function will return a urlencoded string.

Answered By – Anders Lien

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published