0

I have an 'animals' array stored in the database like this:

array(5) {
    [0]=>
    string(4) "Bird"
    [1]=>
    string(3) "Cat"
    [2]=>
    string(5) "Zebra"
    [3]=>
    string(4) "Fish"
    [4]=>
    string(7) "Hamster"
}

...which I can return on the front-end like this...

<?php $animals = get_post_meta( $post_id, 'animals', true ); ?>

<ul>
    <?php
        foreach ( $animals as $animal) { ?>
            <li><?php echo $animal; ?></li>
        <?php
        }
    ?>
</ul>

...and displays like this:

  • Bird
  • Cat
  • Zebra
  • Fish
  • Hamster

But what I need to also do, is display the sting number next to each animal, so the result would look like this:

  • Bird (0)
  • Cat (1)
  • Zebra (2)
  • Fish (3)
  • Hamster(4)

1 Answer 1

2

You could iterate the array using key value syntax.

<ul>
    <?php
        foreach($array as $key=>$value) { ?>
            <li><?php echo $value . " (" . $key . ")"; ?></li>
        <?php
        }
    ?>
</ul>
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.