Index: includes/common.inc
===================================================================
RCS file: /cvs/drupal/drupal/includes/common.inc,v
retrieving revision 1.865
diff -u -p -r1.865 common.inc
--- includes/common.inc	9 Feb 2009 03:29:53 -0000	1.865
+++ includes/common.inc	10 Feb 2009 10:45:21 -0000
@@ -3493,11 +3493,19 @@ function element_children(&$elements, $s
       }
     }
   }
-  // Sort the element if necessary.
+  // Sort the children if necessary.
   if ($sort && $sortable) {
     uasort($children, 'element_sort');
+    // Put the sorted children back into $elements in the correct order, to
+    // preserve sorting if the same element is passed through
+    // element_children() twice.
+    foreach ($children as $key => $child) {
+      unset($elements[$key]);
+      $elements[$key] = $child;
+    }
+    $elements['#sorted'] = TRUE;
   }
-  $elements['#sorted'] = TRUE;
+
   return array_keys($children);
 }
 
Index: modules/simpletest/tests/common.test
===================================================================
RCS file: /cvs/drupal/drupal/modules/simpletest/tests/common.test,v
retrieving revision 1.26
diff -u -p -r1.26 common.test
--- modules/simpletest/tests/common.test	9 Feb 2009 03:29:54 -0000	1.26
+++ modules/simpletest/tests/common.test	10 Feb 2009 10:45:22 -0000
@@ -542,7 +542,15 @@ class DrupalRenderUnitTestCase extends D
     // Confirm that the $elements array has '#sorted' set to TRUE.
     $this->assertTrue($elements['#sorted'], t("'#sorted' => TRUE was added to the array"));
 
-    // Now the same array structure, but with #sorted set to TRUE.
+    // Pass $elements through element_children() and ensure it remains
+    // sorted in the correct order. drupal_render() will return an empty string
+    // if used on the same array in the same request.
+    $children = element_children($elements);
+    $this->assertTrue(array_shift($children) == 'first', t('Child found in the correct order.'));
+    $this->assertTrue(array_shift($children) == 'second', t('Child found in the correct order.'));
+
+
+    // The same array structure again, but with #sorted set to TRUE.
     $elements = array(
       'second' => array(
         '#weight' => 10,
