Main Content
Double Dollars in PHP Archive - Originally posted on "The Horse's Mouth" - 2005-11-02 23:17:57 - Graham Ellis
What does this print?
<?php
$first = "fur";
$last = "feather";
$$first = "yum yum ";
${"$first$last"} = "yikes";
print "$fur $furfeather";
?>
It prints "yum yum yikes".
In PHP, you can write a variable name within a variable name, and that's what I've done in this example.
The variable called "first" is set to contain the word "fur"
The variable who's name is in first - so that's the variable called fur - is set to "yum yum"
The variable called "last" is set to "feather"
The variable who's name is made up of the string in the variable first followed by the string in the varaible last - so that's the variable called furfeather - is set to "yikes".
This is a facility to be used sparingly - it's quite easy to write code that's unmaintainable using such structures, though they can be very useful at times for helping to generalise code.
Some other articles
H999 - Additional PHP Material Image indexer / thumbnail display scripts in PHP Catchable fatal error in PHP ... How to catch, and alternative solutions such as JSON Arrays of arrays - or 2D arrays. How to program tables. Exception handling in PHP If nothing, make it nothing. Extra PHP Examples PHP Techniques - a workshop Flipping images on your web page Script to present commonly used images - PHP Copyright and theft of images, bandwidth and members. More PHP sample and demonstration programs Ordnance Survey Grid Reference to Latitude / Longitude Converting from postal address to latitude / longitude Controlling and labelling Google maps via PHP PHP Standalone - keyboard to screen Drawing hands on a clock face - PHP Drawing dynamic graphs in PHP Sorting people by name in PHP Parallel processing in PHP Dates, times, clickable diarys in PHP Display an image from a MySQL database in a web page via PHP Syntax checking in PHP Reporting on the 10 largest files or 10 top scores PHP - a team member leaves Check your user is human. Have him retype a word in a graphic Hot answers in PHP Presentation, Business and Persistence layers in Perl and PHP PHP Image viewing application PHP - setting sort order with an associative array Merging pictures using PHP and GD Running a Perl script within a PHP page This article Stand alone PHP programs Time calculation in PHP the array returned by preg_match_all More maps Ordnance Survey - using a 'Get a map' What and why for the epoch PHP and natural sorting H103 - Variables, Operators and Expressions A small teaching program - demonstration of principles only Learning to program - variables and constants BODMAS - the order a computer evaluates arithmetic expressions PHP variables - dynamically typed. What does that mean? Do I need to initialise variables - programming in C, C++, Perl, PHP, Python, Ruby or Java. If nothing, make it nothing. Getting rid of variables after you have finished with them This article