I have the following structure:
$text_1 = $this->getValue('value_1');
$text_2 = $this->getValue('value_2');
$text_3 = $this->getValue('value_3')
And also the following:
foreach($text_1 as $t_1)
{
if(!$first)
{
$string_1 .= ",";
}
$first = false;
$string_1 .= $t_1;
}
foreach($text_2 as $t_2)
{
if(!$first)
{
$string_2 .= ",";
}
$first = false;
$string_2 .= $t_2;
}
foreach($text_3 as $t_3)
{
if(!$first)
{
$string_3 .= ",";
}
$first = false;
$string_3 .= $t_3;
}
I was wondering if this could be re-factored to use a counter, like in a for loop, to replace the _1, _2, _3 etc from my code?
Ok so I figured out a way of doing it:
for ($i=1;$i<=12;$i++) {
$choices = $this->getValue('question_'.$i);
$serialized = "";
$first = true;
foreach($choices as $choice)
{
if(!$first)
{
$serialized .= ",";
}
$first = false;
$serialized .= $choice;
}
$this->setValue('question_'.$i, $serialized);
}
This seems to work well!
Well, the foreach-loops can be replaced with implode
.
Other than that, wouldn't it be better to use an array for your $text_??
variables? Eg.:
$text = $this->getValue('value');
foreach ($text as $value) {
$strings[] = implode(",", $value);
}
Hard to give more concrete advise, without the exact context, but that should get you in the right direction.
Yes, you should probably be using an array or map to hold the values and iterating over that, assuming that the values you're dealing with are all the same sort of thing.
I hope this one helps u...
$arrOutput = compact('text_1', 'text_2', 'text_3');
foreach($arrOutput as $t1)
{
$out1[] = implode(",", $t1);
}
print_r($out1);