I have a set of categories I want to loop through, and set a dynamic variable/array as the page loops.
The code I currently have is:
foreach($categories as $category)
{
$category_ads[] = Advert::listforPageArea(2, 1, $category['id']);
}
The Advert::listforPageArea function returns an object of an advert based on what category is chosen.
I want to be able to calculate the expiry date of each advert to use elsewhere.
I’m struggling to explain exactly what I want, but I simply want to set custom content within a loop.
What you’re searching for is called ‘variable variables’.
See http://foundationphp.com/blog/2010/12/18/understanding-php-variable-variables/
The linked blog entry also answers the question of variable scope (contrary to Geoffroy’s answer, variable variables are valid outside of the loop they are created in) and states (correctly) that this method is highly insecure without validating the variable names.
Could you go with an array within an array instead?
$arr['cat1']['cat2']EDIT: how to do this with multidimensional arrays (see http://php.net/manual/en/language.types.array.php)
!!! Important: You’re using
$categorylike a variable one time and like an associative array the other time. You can’t simply evaluate an array to a string. I guess your array$categorymay contain some fieldname?, as it seems to contain a field namedid. You’d have to use that field name in$ads[$category['field???']][]or your lineAdvert::listforPageArea(2, 1, $category['id']);is not correct.