How to remove duplicate values in PHP loop?

Viewed 68

I am using Word Press with Advanced Custom Fields and have a loop to add a field (location) to an Options tag.

There are several posts with the same location, so if I loop normally I get results such as Toronto, Ottawa, Toronto, Montreal, Toronto, Toronto, Montreal, etc. I want it so it only has "Toronto, Ottawa, Montreal".

I tried to add the values to an array, then use array_unique(), but I do not know how to separate the values in the array.

My code -

<?php while( have_posts() ) : the_post(); ?>
    <?php while ( have_rows( 'location_info' ) ) : the_row(); ?>
        <?php $locations[] = get_sub_field( 'location' ); ?>
        <option><?php echo implode('', array_unique($locations)); ?></option>
    <?php endwhile; ?>
<?php endwhile;?>

But this prints

<option>TorontoOttawaMontreal</option>
<option>TorontoOttawaMontreal</option>
<option>TorontoOttawaMontreal</option>

I need it to print

<option>Toronto</option>
<option>Ottawa</option>
<option>Montreal</option>
3 Answers

Added htmlentities and strip tags for security because it seems like this data must be coming from users.

<? foreach( array_unique( $locations ) as $location ) { ?>
    <option value="<?= htmlentities( $location ) ?>"><?= strip_tags( $location ) ?></option>;
<? } ?>

You can use in_array() function to check if value exists in array. Try below code snippet.

<select name="field_name">
<?php
$locations = [];
while( have_posts() ) :
    the_post();
    while ( have_rows( 'location_info' ) ) :
        the_row(); 
        $loc = get_sub_field( 'location' );
        if( in_array( $loc, $locations ) ) {
            continue;
        }
        $locations[] = $loc;
        ?>
        <option value="<?php echo esc_attr( $loc ); ?>"><?php echo esc_html( $loc ); ?></option>
    <?php endwhile; ?>
<?php endwhile; ?>
<?php unset( $locations ) ?>
</select>
<?php while( have_posts() ) : the_post(); ?>
    <?php while ( have_rows( 'location_info' ) ) : the_row(); ?>
        <?php $locations[] = get_sub_field( 'location' ); ?>
    <?php endwhile; ?>
<?php endwhile;?>

<?php $locations_options = array_unique($locations); ?>
<select>
    <?php foreach( $locations_options as $location ): ?>
        <option value="<?php echo $location; ?>"><?php echo $location; ?></option>
    <?php endforeach; ?>
</select>
Related