Trying to change $_POST key

Hi All,

I am trying this bit of code to remove the xx from the beginning on the required fields i.e. xxBarcode.

foreach($_POST as $key => $value) {
	if ((preg_match_all ("|^[xx]|","$key",$out))){
	$keynew = substr_replace($key,"",+0 , +2);
	$_POST[$key] = $keynew;
	echo 'THE NEW KEY '.$_POST[$key].'<br>'; // this is fine and displays Barcode
echo '<pre>'; print_r($_POST); echo '</pre>'; // this is still showing xxBarcode

I just can’t see what is going wrong or why print_r is not showing the new key values.

If anyone can point out what I am doing wrong,that would be great.


You’re not creating a new key, you’re replacing the value there. Don’t you want
$_POST[$keynew] = $value;

Q Monkey, you are correct and thanks but that doesnt solve my problem unfortunatly

this is what I have in the array
( key value)
[xxBarcode] => 89073209848290

I am trying to remove the xx from barcode so that print_r just shows Barcode.

Now my problem makes more sense to me, thanks for pointing out the $value part, I need to change the key somehow.


I’m a little confused, do you mean like this?

$_POST = array(
    'xxABarcode' => 123456789,
    'xxSomeBarcode' => 123456789,
    'xxAnotherBarcode' => 123456789,

foreach ($_POST as $mKey => $mValue)
    $aProcessed[ preg_replace('~^xx~','',$mKey) ] = $mValue;

$_POST = $aProcessed;

    [ABarcode] => 123456789
    [SomeBarcode] => 123456789
    [AnotherBarcode] => 123456789

You nearly had it already but the one line $_POST[$key] = $keynew; should be like the one I posted. Then you’ll probably want to get rid of the ‘xxBarcode’ type keys with unset($_POST[$key]); right after, or just make a new array for the new keys instead of putting them into POST.

As a side note, instead of all the regex I’d do something like

 if (0 === strpos($key,"xx")) {
    $keynew = substr($key,2);

Awesome, I have been trying many things.
All I had to do was look at SilverBulletUK’s, code and it was crystal clear and it was as simple as changing
$_POST[$key] = $value;
$_POST[$keynew] = $value;

in the loop and yes I ended up with xxBarcode and Barcode with my way of doing it.

Thanks heaps, your code examples look a lot better than my clunky stuff and I learned more than I bargained for.



QMonkey, I just saw a similar example of strpos and was wondering how it would work for me, awesome timing

I would recomend you treat php’s superglobals as read only variables. Don’t modify them. Just make a new array which contains the processed values.