Reindex an Array in PHP

Occasionally, you may need to arbitrarily reindex an array of data in PHP. WordPress doesn’t really provide a function for doing this, so I put together this code snippet:

This utility function can be useful for any PHP-based project. It comes in handy when you want to take an indexed array and convert it into an associative array.

For example, taking a collection of posts and indexing them by ID becomes super simple:

$posts = get_posts();
$posts_by_id = index_by( 'ID', $posts );

This function will work equally well with an array of objects or an array of arrays.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.