修改$ _POST数组中的项目

I'm using CodeIgniter to validate form data, and then posting it to a third party site using the php header() function with the $_POST key-value pairs as URL parameters. So for example:

'first_name' => 'chris' 'area_code' => '555' 'phone_number => '555-5555'

... would become 'http://thirdpartysite.com?first_name=chris&area_code=555&phone_number=555-5555'.

The most "elegant" way I can think to do this is to iterate over the $_POST array like this...

$formValues = $this->input->post(NULL, TRUE);
foreach($formValues as $key => $value) 
{
    $postURL .= $key . '=' . $value . '&';
}

The problem is that the third party site needs to take a whole phone number as one parameter; it can't take "area code" and "phone number" broken up into two pieces as I have it on my form. So what I need to do is concatenate area_code and phone_number and store it in a new variable that gets appended to the URL string.

What's the best way to do this? I was thinking of maybe adding an if, else statement to the foreach loop that would check if the key is "area_code" or "phone_number" and do the proper actions, but is there a better way to do this? Is there a native way in php or CodeIgniter to modify the $_POST array before iterating over it?

Thank you!!

You can modify the $_POST array directly in the same way as any other array.

You could do:

$_POST['phone'] = $_POST['area_code'] . $_POST['phone_number'];
unset($_POST['area_code']);
unset($_POST['phone_number']);

then run your existing code.

However I it's not a good ideal to deal with user input in this way - you should really be taking only the fields you require to pass to the third party URL otherwise someone malicious could use your script to attack the third party server.

You could just add the area code to the beginning of the phone number in the formValues array, then remove the area code element:

$formValues = $this->input->post (NULL, TRUE);

$formValues['phone_number'] = $formValues['area_code'] . '-' . $formValues['phone_number'];
unset ($formValues['area_code'];

foreach ($formValues as $key => $value) 
{
    $postURL .= $key . '=' . $value . '&';
}

Keep is simple:

$formValues = $this->input->post(NULL, TRUE);
$postUrl = $address . "?first_name=" . $formValues["first_name"] . "&phone=" . $formValues["area_code"] . "-" . $formValues["phone_number"];

This is how I would approach this.