Connecting Tech Pros Worldwide Help | Site Map

PHP: Using variable variables.

  #1  
Old April 28th, 2008, 07:37 AM
Markus's Avatar
Moderator
 
Join Date: Jun 2007
Location: York, England, with wolves.
Posts: 4,859
Using the code below you can turn array indices into variables that can be accessed as a normal variable would be.



Expand|Select|Wrap|Line Numbers
  1. <?php
  2. /**
  3. * @author      Mark Skilbeck - MAHCUZ.COM
  4. * @title    PHP: Variable variables.
  5. **/
  6.  
  7. $array = array("Name" => "Foo", "Age" => 21);
  8.  
  9. foreach( $array AS $Key => $Val )
  10. {
  11.     $var   = $Key;
  12.     $$var  = $Val;
  13. }
  14.  
  15. // the array can now be accessed
  16. // by using:
  17. //
  18. // echo $array_key;
  19.  
  20. echo "Name: $Name - Age: $Age";
  21. // prints Name: Foo - Age: 21
  22. ?>
  23.  



  #2  
Old April 29th, 2008, 09:39 PM
Markus's Avatar
Moderator
 
Join Date: Jun 2007
Location: York, England, with wolves.
Posts: 4,859

re: PHP: Using variable variables.


Just found out you can use the extract() function instead.

My work is pointless!
  #3  
Old May 5th, 2008, 04:22 PM
ronverdonk's Avatar
Moderator
 
Join Date: Jul 2006
Location: The Netherlands
Posts: 4,139

re: PHP: Using variable variables.


Quote:
Originally Posted by markusn00b
Just found out you can use the extract() function instead.
My work is pointless!
No it is not. At leastt you showed how you can use and manipulate dynamic variable names.

Ronald
  #4  
Old May 20th, 2008, 02:13 PM
hsriat's Avatar
Expert
 
Join Date: Jan 2008
Location: Bath, UK
Posts: 1,609

re: PHP: Using variable variables.


Quote:
Originally Posted by ronverdonk
At least you showed how you can use and manipulate dynamic variable names.

Ronald
Yeah, I never knew about $$ trick.

Thanks Mark...
Reply


Similar Threads
Thread Thread Starter Forum Replies Last Post
Variable Variables in Classes Alan Little answers 10 May 20th, 2006 04:15 PM
variable variables question Dave answers 3 February 13th, 2006 11:05 PM
php using javascript objects phdfromic@yahoo.com answers 1 January 9th, 2006 01:05 PM
Using variable names stored in database fields. bofh@visi.com answers 4 July 17th, 2005 05:22 AM