Sam Skirrow
Sam Skirrow

Reputation: 3697

PHP echo incremental number for each item in an array

I am using wordpress and am trying to create a dropdown list of users as a metabox within a custom post type.

I have been able to create the dropdown list as follows:

<?php
    $users = get_users();
    // Array of WP_User objects.
    foreach ( $users as $user ) {
        echo '<option value="select" >' . esc_html( $user->display_name ) . '</option>';
    }
?>

However, the value needs to have an incremental number for each result, i.e. select-1, select-2, select-3 - how can I add this to my results?

Upvotes: 1

Views: 218

Answers (2)

Nico
Nico

Reputation: 7256

if i understand correctly try this :

<?php
    $users = get_users();
    // Array of WP_User objects.
    $counter = 1;

    foreach ( $users as $user ) {
        $value = "value".$counter;
        echo '<option value="'.$value.'" >' . esc_html( $user->display_name ) . '</option>';
    $counter++;
    }
?>

Upvotes: 1

Jan
Jan

Reputation: 43169

Just use an integer which gets incremented.

<?php
    $users = get_users();
    $i = 0;
    // Array of WP_User objects.
    foreach ( $users as $user ) {
        echo "<option value='select-$i' >" . esc_html( $user->display_name ) . "</option>";
        $i++;
    }
?>

Alternative: use a for loop directly:

<?php
    $users = get_users();
    // Array of WP_User objects.
    for ($i=0;$i<count($users);$i++) {
        $user = $users[$i];
        echo "<option value='select-$i' >" . esc_html( $user->display_name ) . "</option>";
    }
?>

Upvotes: 2

Related Questions