By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
437,913 Members | 1,305 Online
Bytes IT Community
Submit an Article
Got Smarts?
Share your bits of IT knowledge by writing an article on Bytes.

PHP: Using variable variables.

Markus
Expert 5K+
P: 6,050
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.  
Apr 28 '08 #1
Share this Article
Share on Google+
3 Comments


Markus
Expert 5K+
P: 6,050
Just found out you can use the extract() function instead.

My work is pointless!
Apr 29 '08 #2

ronverdonk
Expert 2.5K+
P: 4,258
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
May 5 '08 #3

hsriat
Expert 100+
P: 1,654
At least you showed how you can use and manipulate dynamic variable names.

Ronald
Yeah, I never knew about $$ trick.

Thanks Mark...
May 20 '08 #4