Dynamic Variables

I have an array called $events full of different event names.
One row might look like this (id = 2, name = ‘Baseball’, etc.) as well as other fields

How can i create variables within a foreach statement that have the name from the values within the array. That I can use outside of the foreach statement?

For example.


foreach ($events as $event)
{

   $Baseball = 1;

}

The variable $Baseball needs to change each time the foreach is processed

what do you think?

i know, i was saying your code is good practice but not NEEDED

Thanks bro, your first solution works great! :slight_smile:

Cheers

Or:


foreach ($events as $event) {
   ${$event['name'] . 'paid'} = whatever;
   ${$event['name'] . 'unpaid'} = whatever;
}

PS. If you need constructions like these, it usually indicates you’re doing something wrong …

You might try this (don’t know if it works)


${$event['name'].$paid}

If not, you can always create the two variable names and then create the variables:


foreach ($events as $event) {
   $paid = $event['name'] . 'paid';
   $unpaid = $event['name'] . 'unpaid';
   $$paid = whatever;
   $$unpaid = whatever;
}

Like my example above. I need to save 2 values for each event. Paid and unpaid.

if I try:


$$event['name'].$paid = whatever;
$$event['name'].$unpaid = whatever;

Every event ends up with the same value as the last event.

What gives?

You wouldn’t get any warnings from what I posted.

How can I add some text to the end of the variable name.

I will be counting 2 separate things in the database and need to assign them to a variable for each event.

For example:

if $$event = Baseball

how can I get

Baseballpaid and Baseballunpaid

guido is right, you don’t NEED to, but it is good practice and will avoid warnings
you should be developing with warnings on, as it will help you spot problems quickly

I miss understood the question. Don’t have a fit. :injured:

$events = array(
    array('id' => 1, 'name' => 'Baseball')
);
foreach ($events as $event) {
    $$event['name'] = $event['id'];
}
echo $Baseball; // equals 1

No you don’t

Thanks this is exactly what I needed.

Cheers

In order to use a variable value outside of a loop you need to declare it BEFORE you create the loop.


$baseball = 0;
foreach($events as $event) {
  //Do whatever you want here with $baseball;
  //etc..
}

//We're done iterating so print it:
echo $baseball;

$$event