should i use a loop or write each repetition

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • guillermobytes
    New Member
    • Jan 2010
    • 77

    should i use a loop or write each repetition

    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:

    Code:
    	$partsCopy = $this->_parts;
    	$pos = array_search($newOrder[0], $this->_order);
    	$this->_parts[0] = $partsCopy[$pos];
    	$pos = array_search($newOrder[1], $this->_order);
    	$this->_parts[1] = $partsCopy[$pos];
    	$pos = array_search($newOrder[2], $this->_order);
    	$this->_parts[2] = $partsCopy[$pos];
    or i should do this :

    Code:
    $partsCopy = $this->_parts;
    for ($i = 0; $i < 3; $i++) {
    	$pos = array_search($newOrder[$i], $this->_order);
    	$this->_parts[$i] = $partsCopy[$pos];
    }
    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
  • Atli
    Recognized Expert Expert
    • Nov 2006
    • 5062

    #2
    Hey.

    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:
    [code=php]$partsCopy = $this->_parts;
    $count = count($newOrder );
    for ($i = 0; $i < $count; $i++) {
    $pos = array_search($n ewOrder[$i], $this->_order);
    $this->_parts[$i] = $partsCopy[$pos];
    }[/code]
    Now the code would work no matter how many items $newOrder has.

    Comment

    • guillermobytes
      New Member
      • Jan 2010
      • 77

      #3
      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?

      Comment

      • Markus
        Recognized Expert Expert
        • Jun 2007
        • 6092

        #4
        You could, of course, skip the need to count the elements by using a foreach loop.

        Code:
        foreach ($this->_parts as $key => $data) {
            // ...
        }

        Comment

        Working...