Re: array to var - with different name

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

 



On Thu, Jan 20, 2011 at 3:09 PM, Tommy Pham <tommyhp2@xxxxxxxxx> wrote:
> On Thu, Jan 20, 2011 at 2: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
>>
>>
>> --
>> D Brooke
>>
>
> foreach ($_GET as $key => $value) $$key = $value;
> foreach ($_POST as $key => $value) $$key = $value;
>
> or
>
> foreach ($_REQUEST as $key => $value) $$key = $value;
>
> short-circuited one-liners :)
>
> Regards,
> Tommy
>

akk... wrong clicked before I had a chance to fix the code. anyway,

foreach ($_GET as $key => $value) if (substr($key, 0, 2) == 'f_')
${'t_'.substr($key, 2)} = $value;

-- 
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