Connecting Tech Pros Worldwide Forums | Help | Site Map

PHP: Using variable variables.

Markus's Avatar
Moderator
 
Join Date: Jun 2007
Location: York, England, with wolves.
Posts: 4,938
#1   Apr 28 '08
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.  



Markus's Avatar
Moderator
 
Join Date: Jun 2007
Location: York, England, with wolves.
Posts: 4,938
#2   Apr 29 '08

re: PHP: Using variable variables.


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

My work is pointless!
ronverdonk's Avatar
Moderator
 
Join Date: Jul 2006
Location: The Netherlands
Posts: 4,139
#3   May 5 '08

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
hsriat's Avatar
Expert
 
Join Date: Jan 2008
Location: Bath, UK
Posts: 1,609
#4   May 20 '08

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