Saving array values for a secondary foreach loop Although used within the WordPress platform, this is PHP focussed question.

I have an array of child posts, some have content, some don't. My client wishes to display the posts in alphabetical order, but posts without content are to be positioned at the end (still in A-Z order).

My solution is to assign posts that lack content to an array, use continue to move the main array counter forward and then foreach over the the new array at the end:

&lt;?php

    $child_pages = pp_get_child_pages();

    if ( count( $child_pages ) != 0 ) :

        $empty_child_pages = array();

        echo '&lt;div class="row quick-links page-links primary-content-item"&gt;';

        foreach ( $child_pages as $post ) :

            setup_postdata( $post );

            if ( $post-&gt;post_content == "" ) {
                $empty_child_pages[] = $post;
                continue;
            }

            pp_get_template_part( 'content', 'child-page' );

        endforeach;

        foreach ( $empty_child_pages as $post ) :

            setup_postdata( $post );

            pp_get_template_part( 'content', 'child-page' );

        endforeach;

        echo '&lt;/div&gt;';

    endif;

    wp_reset_postdata();

?&gt;


Is there a more efficient way to write this?

Would you modify the array during the initial 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.