By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,516 Members | 1,176 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,516 IT Pros & Developers. It's quick & easy.

should i use a loop or write each repetition

P: 77
hi, i have a code that is repeated 3 times and i wonder if i better use a for loop or just leave it explicitly coded. here is the code:

Expand|Select|Wrap|Line Numbers
  1.     $partsCopy = $this->_parts;
  2.     $pos = array_search($newOrder[0], $this->_order);
  3.     $this->_parts[0] = $partsCopy[$pos];
  4.     $pos = array_search($newOrder[1], $this->_order);
  5.     $this->_parts[1] = $partsCopy[$pos];
  6.     $pos = array_search($newOrder[2], $this->_order);
  7.     $this->_parts[2] = $partsCopy[$pos];
or i should do this :

Expand|Select|Wrap|Line Numbers
  1. $partsCopy = $this->_parts;
  2. for ($i = 0; $i < 3; $i++) {
  3.     $pos = array_search($newOrder[$i], $this->_order);
  4.     $this->_parts[$i] = $partsCopy[$pos];
  5. }
i don't know which is the best approach since the count is so little and the code inside the loop too.
if you have any suggestions let me know
Mar 23 '10 #1
Share this Question
Share on Google+
3 Replies

Expert 5K+
P: 5,058

Ideally you would want to avoid hard-coding the number of repetitions needed. It allows you to dynamically change the output without having to change the code.

In your code, does the $newOrder have more than 3 elements? If the number of elements in $newOrder changed, would the code have to reflect that?
If so, the you might want to do something more like:
Expand|Select|Wrap|Line Numbers
  1. $partsCopy = $this->_parts;
  2. $count = count($newOrder);
  3. for ($i = 0; $i < $count; $i++) { 
  4.     $pos = array_search($newOrder[$i], $this->_order); 
  5.     $this->_parts[$i] = $partsCopy[$pos]; 
  6. }
Now the code would work no matter how many items $newOrder has.
Mar 24 '10 #2

P: 77
Thanks Atli,
no the number of repetitions will never change.
the parts here are those of a Date (day, month, year) and the program does not care about time in minutes or anything like that, so i'm sure 100% that the parts will always be 3.

so given that the parts will always be 3 and that the repeated code is very short, is it better to use a for loop or just hard code the 3 repetitions?
Mar 24 '10 #3

Expert 5K+
P: 6,050
You could, of course, skip the need to count the elements by using a foreach loop.

Expand|Select|Wrap|Line Numbers
  1. foreach ($this->_parts as $key => $data) {
  2.     // ...
  3. }
Mar 24 '10 #4

Post your reply

Sign in to post your reply or Sign up for a free account.