Andy Tait
Andy Tait

Reputation: 199

Set dynamic variables in foreach loop

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.

Upvotes: 0

Views: 4306

Answers (2)

Martin Hennings
Martin Hennings

Reputation: 16846

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)

$ads = array(); // not explicitly needed, but clarifying
// ... some code
foreach($categories as $category)
{
    if(!array_key_exists($category, $ads)) { $ads[$category] = array(); } // not explicitly needed
    $ads[$category['name?']][] = Advert::listforPageArea(2, 1, $category['id']);
    // or (see comment below)
    $ads[$category][] = Advert::listforPageArea(2, 1, getCategoryField($category, 'id'));
}

!!! Important: You're using $category like 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 $category may contain some field name?, as it seems to contain a field named id. You'd have to use that field name in $ads[$category['field???']][] or your line Advert::listforPageArea(2, 1, $category['id']); is not correct.

Upvotes: 1

Jaffa
Jaffa

Reputation: 12700

The content you set in your loop will be restricted to that loop. So it won't be usable elsewhere (as far as I remember).

If you want you can create a variable like :

//In the foreach loop
$cat_name = "whatever";
$var_name = $cat_name . "_expiryDate";

$$var_name = 5 /* Calulcate the expiry date here */;

To be able to access your variables elsewhere, you will need to store the value outside of the loop, such as in an associative array.

One other solution would be to include the expiry date in the Advert object, or expose a method to get it in the class.

Upvotes: 0

Related Questions