terrid25 Posted November 4, 2010 Share Posted November 4, 2010 Hi I have a method, which is pretty large. It has a lot of 'duplicate' code and I'd like to refactor it: protected function doSave($con = null) { $choices_1 = $this->getValue('question_1'); $choices_2 = $this->getValue('question_2'); $choices_3 = $this->getValue('question_3'); $choices_4 = $this->getValue('question_4'); $serialized_ = ""; $first = true; foreach($choices_1 as $choice_1) { if(!$first) { $serialized_1 .= ","; } $first = false; $serialized_1 .= $choice_1; } foreach($choices_2 as $choice_2) { if(!$first) { $serialized_2 .= ","; } $first = false; $serialized_2 .= $choice_2; } foreach($choices_3 as $choice_3) { if(!$first) { $serialized_3 .= ","; } $first = false; $serialized_3 .= $choice_3; } foreach($choices_4 as $choice_4) { if(!$first) { $serialized_4 .= ","; } $first = true; $serialized_4 .= $choice_4; } $this->setValue('question_1', $serialized_1); $this->setValue('question_2', $serialized_2); $this->setValue('question_3', $serialized_3); $this->setValue('question_4', $serialized_4); return parent::doSave($con); } You can see most of the arrays have a '_1', '_2' after them, the same goes for the $serialized variables. What I'd like is to maybe have some kind of loop, that will reduce my code down, and rather than me typing all the code above, possibly increment the '_1', '_2' part upto the 5 iterations. Can anyone provide some help/code for me to carry this out? Regards Quote Link to comment Share on other sites More sharing options...
mikecampbell Posted November 4, 2010 Share Posted November 4, 2010 Here you go! protected function doSave($con = null) { for ($i=1;$i<=5;$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); } return parent::doSave($con); } Quote Link to comment Share on other sites More sharing options...
terrid25 Posted November 4, 2010 Author Share Posted November 4, 2010 Excellent!! Thank you Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.