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
You can use in_array() function to check if value exists in array. Try below code snippet.
Added htmlentities and strip tags for security because it seems like this data must be coming from users.