How to order an ACF repeater field in descending order by key

The problem:

```php
<?php if ( have_rows( 'repeater_field' ) ) while ( have_rows( 'repeater_field' ) ) : the_row(); ?>
    <?php
        $name = get_sub_field( 'name' );
        $age = get_sub_field( 'age' );
    ?>
	
    <p><?php echo $name; ?></p>
    <p><?php echo $age; ?></p>
<?php endwhile; ?>
```

This only gets you the normal, ascending order for those repeater rows.
But what if you need to reverse the order of those rows, making first the last and vice-versa?

The Advanced Custom Fields documentation gives an example, but that didn't work at the time of this writing. They instruct you to use the `get_field()` function for the main repeater field, but for some reason that returns null on a repeater field.

What I've found to work was to use the `get_sub_field()` to get the field and the krsort() php method which sorts an array by key in descending order.

```php
<?php
    $repeater = get_sub_field('repeater_field');
    krsort($repeater);
?>
<?php foreach ($repeater as $row): ?>
    <p><?php echo $row['name']; ?></p>
    <p><?php echo $row['age']; ?></p>
<?php endforeach; ?>
```

One thing to note is that with this method you need to change the way you access those variables.

Zeno Popovici
17 Dec 2021
« Back to post