0

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 ...

7 Answers 7

1

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

$var = "counter".$weekDay.$ii;
$$var = 0;
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

1

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;

Comments

0

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;
    }
}

Comments

0
$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;
   }

}

Comments

0

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;
   }
}
?>

Comments

0

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;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.