Home > OS >  How to remove duplicate values in PHP loop?
How to remove duplicate values in PHP loop?

Time:08-29

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>

CodePudding user response:

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

<?php while( have_posts() ) : the_post(); ?>
    <?php while ( have_rows( 'location_info' ) ) : the_row(); ?>
        <?php 
        $location = get_sub_field( 'location' );
        if( in_array($location, $locations) ) {
            continue;
        }
        $locations[] = $location;
        ?>
        <option><?php echo $location; ?></option>
    <?php endwhile; ?>
<?php endwhile; ?>

CodePudding user response:

You have to write it like this:

<?php
while ( have_posts() ) :
    the_post();
    while ( have_rows( 'location_info' ) ) :
        the_row();
        $locations = get_sub_field( 'location' );
        $locations = ! empty( $locations ) && is_array( $locations ) ? array_filter( array_unique( $locations ) ) : array();
        ?>
        <select name="select_name" id="select_id">
            <?php foreach ( $locations as $location ) : ?>
                <option value="<?php echo esc_attr( $location ); ?>"><?php echo esc_html( $location ); ?></option>
            <?php endforeach; ?>
        </select>
        <?php
    endwhile;
endwhile;
?>
  • Related