Susanne92
Susanne92

Reputation: 217

Dynamic PHP-Variable

My target: create dynamic variables like

$counterMon00 = 0;
$counterMon01 = 0;
$counterThu23 = 0;

My code until now:

$array_days = ["Mon","Tue","Wed","Thu","Fri"];
for ($i = 0; $i < sizeof($array_days); $i++)
{
   $weekDay = (String) $array_days[$i];
   for($ii = 7; $ii < 10; $ii++)
   {
   "counter".${$weekDay}.${$ii} = 0;
   }
}

Can You help my with this line

"counter".${$weekDay}.${$ii} = 0;

I tried different solution but nothing worked ...

Upvotes: 0

Views: 92

Answers (7)

Nisarg
Nisarg

Reputation: 3262

Try This

$array_days = ["Mon","Tue","Wed","Thu","Fri"];
for ($i = 0; $i < sizeof($array_days); $i++)
{

//   $weekDay = $array_days[$i];
    for($ii = 0; $ii < 5; $ii++)
    {
    //echo "counter".${$weekDay}.${$ii} = 0;
        $a = "counter".$array_days[$i].$i.$ii;
        $$a = 0;
    }
}

Upvotes: 0

Kalaiyarasan
Kalaiyarasan

Reputation: 13384

Please try the following you make a mistake in the array declaration also

<?php
$array_days = array("Mon","Tue","Wed","Thu","Fri");
for ($i = 0; $i < sizeof($array_days); $i++)
{
  $weekDay = (String) $array_days[$i];
   for($ii = 7; $ii < 10; $ii++)
   {
    $var = "counter".$weekDay.(String)$ii;
    $$var = 0;
   }
}
?>

Upvotes: 0

Rajeev Ranjan
Rajeev Ranjan

Reputation: 4142

$array_days = array("Mon","Tue","Wed","Thu","Fri");
for ($i = 0; $i < count($array_days); $i++)
{
   $weekDay = (String) $array_days[$i];
   for($ii = 7; $ii < 10; $ii++)
   {
   $var="counter".$weekDay.$ii;
   $$var;
   }

}

Upvotes: 0

deceze
deceze

Reputation: 522101

You want an array! That's exactly what they're for. Variable variables are a bad idea in 99% of all cases.

$counter = [];
$days    = ["Mon","Tue","Wed","Thu","Fri"];

foreach ($days as $day) {
    foreach (range(7, 9) as $i) {
        $counter[$day][$i] = 0;
    }
}

Upvotes: 0

Jim
Jim

Reputation: 22656

Try using variable variables:

$varName = "counter".${$weekDay}.${$ii};
$$varName = 0;//Note the $$

You also may want to look into building an array rather than the above as this would be easier (in my opinion at least). Something like an array mapping weekdays to counts i.e.

$arr["Mon"][3] = 0;

Upvotes: 1

Yuust Armts
Yuust Armts

Reputation: 11

${"counter".$weekDay.$ii} = 0;

Upvotes: 1

Anigel
Anigel

Reputation: 3437

You need to have the variable set as a single string before using it.

$var = "counter".$weekDay.$ii;
$$var = 0;

Upvotes: 1

Related Questions