RE: [PHP] array to var - with different name
| From: | Tommy Pham | Date: | Thu, 20 Jan 2011 23:38:01 +0000 |
| Subject: | RE: [PHP] array to var - with different name | ||
| References: | 1 2 3 4 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-310932@lists.php.net to get a copy of this message | ||
> -----Original Message-----
> From: Donovan Brooke [mailto:lists@euca.us]
> Sent: Thursday, January 20, 2011 3:29 PM
> Cc: php-general@lists.php.net
> Subject: Re: [PHP] array to var - with different name
>
> Tommy Pham wrote:
> [snip]
> >> 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;
>
>
> Tommy, excellent.. I had just rewrote your first suggestion:
>
> foreach ($a_formvars as $key => $value) ${str_replace('f_', 't_',$key)}
> =
> $value;
>
> (which works)
> but I like that you are only affecting the vars that *begin* with $match. I
> suppose the above would also work with $_REQUEST.
>
>
>
> Shawn, I don't know if I have a good reason, other than I rather like
> working with string vars instead of array vars from $_REQUEST for
> (sticky forms and conditionals). I can check/verify them as well in the
> process.
>
> Thanks to all that posted.. I always learn from the "skin the cat" game.
>
> Donovan
>
>
> --
> D Brooke
>
I advice strongly against str_replace if you're looking specifically 'f_' at the
__beginning__ of the string. substr would guarantee it.
Regards,
Tommy