Saving array values for a secondary foreach loop
Your approach seems fine, assuming that the entries in $child_pages are the correct order. I mention that because you mentioned the ordering requirement in the description, but I don't see any supporting logic in the posted code.



If you need to sort the entries yourself, another solution can be sorting using usort() and a custom comparator function:


if the second post is empty, then the first is smaller
else if the first part is empty, then the second is smaller
else perform regular alphabetic comparison


Using such comparator, empty posts will get sorted to the end.