Re: array to var - with different name

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On 01/20/2011 04:28 PM, Donovan Brooke wrote:
> Hello again!
> 
> I'm trying to find a good way to convert array key/value's to
> variable name values... but with the caveat of the name being
> slightly different than the original key
> (to fit my naming conventions).
> 
> first, I (tediously) did this:
> 
> -------
> if (isset($_GET['f_action'])) {
>   $t_action = $_GET['f_action'];
> }
> 
> if (isset($_POST['f_action'])) {
>   $t_action = $_POST['f_action'];
> }
> 
> if (isset($_GET['f_ap'])) {
>   $t_ap = $_GET['f_ap'];
> }
> 
> if (isset($_POST['f_ap'])) {
>   $t_ap = $_POST['f_ap'];
> }
> -------
> 
> Instead, I wanted to find *all* incoming "f_" keys in the POST/GET
> array, and convert them to a variable name consisting of "t_" in one
> statement.
> 
> I then did this test and it appears to work (sorry for email line breaks):
> 
> ---------
> $a_formvars = array('f_1' => '1','f_2' => '2','f_3' => '3','f_4' =>
> '4','f_5' => '5','f_6' => '6',);
> 
> $t_string = "";
> foreach ($a_formvars as $key => $value) {
>   if (substr($key,0,2) == 'f_') {
>     $t_string = $t_string . "t_" . substr($key,2) . "=$value&";
>     parse_str($t_string);
>   }
> }
> ---------
> 
> I figure I can adapt the above by doing something like:
> 
> $a_formvars = array_merge($_POST,$_GET);
> 
> However, I thought I'd check with you all to see if there is something
> I'm missing. I don't speak PHP that well and there may be an easier way.
> 
> Thanks,
> Donovan
> 
> 

I'm sure you have a good reason for doing this?  It is needlessly adding
complexity, but here is a one liner (not tested):

extract(array_combine(str_replace('f_', 't_', array_keys($_POST)),
array_values($_POST)));

-- 
Thanks!
-Shawn
http://www.spidean.com

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux