Thursday, February 28, 2008
I always get stuck on one problem with PHP and that is referencing dynamically created array variables. Imagine I have an array of values, say country codes: 'uk,us,de,es' and I want to output data into array variables that have the name $array_countrycode.It took me a while to get to the bottom of this, I knew it had something to do with Variable Variables but the documentation doesn't really cover this kind of example. Eventually I found the solution I was looking for:
${"array_{$code}"}
I have the country codes stored in an array which I loop through:
$country_codes = array("au","de","es","fr","it","nl","uk","us");
foreach($country_codes as $code) {
// then I can reference the array to do whatever I like
${"array_{$code}"}
// would reference $array_au, $array_de etc.
}
This might be old news to some people but it had me scratching my head for quite a while!
Jon 10:22 AM Permalink
