Rob
Rob

Reputation: 6370

Getting reverse array to work

In reference to this question, I'm struggling to reverse an array. I've tried the following but don't think this is correct, where am I going wrong?

<?php $rows = get_field('news');
    $counter = 1;
    $rows_full = array_reverse($rows);
    foreach($rows as $row) { ?>
        <p style="margin-bottom:20px;font-size:14px;"><?php echo $row['news_description']; ?></p>
<?php $counter++ } ?>

Upvotes: 0

Views: 96

Answers (5)

Ayush
Ayush

Reputation: 42440

array_reverse does not reverse the array in-place, but instead returns a new array that is reversed.

$arr = array(1,2,3,4);
$rev_arr = array_reverse($arr);

print_r($arr);         // prints [1,2,3,4,5]
print_r($rev_arr);     // prints [5,4,3,2,1]

Upvotes: 1

Matt Cain
Matt Cain

Reputation: 5768

You're reversing the array and then never using it. Try this instead:

foreach($rows_full as $row) { ...

Upvotes: 1

Prasanth Bendra
Prasanth Bendra

Reputation: 32730

In foreach you are using $rows change it to $rows_full

$rows_full = array_reverse($rows);
    foreach($rows_full as $row) { ?>

Upvotes: 0

Hard worker
Hard worker

Reputation: 4046

This line:

 foreach($rows as $row) { ?>

Should be:

foreach($rows_full as $row) { ?>

Upvotes: 1

GautamD31
GautamD31

Reputation: 28763

Change like this

 $rows_full = array_reverse($rows);
foreach($rows_full as $row) { ?>

Upvotes: 5

Related Questions