phparrayswordpressarray-unique

How to stop duplicates in foreach loop with PHP?


I am getting a list categories names based on which tag is selected in WordPress, the code all works and returns a list of categories but I can't get the code to stop the duplicate category names.

Please see my code below:

<?php
    // Get the categories
    $terms = get_terms( array(
      'taxonomy' => 'category',
      'hide_empty' => 0,
      'parent' => $catparid,
    ) );

    // Loop through them
    foreach($terms as $term) {
    // Get the posts in that category with the required tag
      $args = array(
        'category_name'    => $term->name,
        'tax_query'      => array(
         array(
           'taxonomy'  => 'post_tag',
           'field'     => 'slug',
           'terms'     => $cattagfilter
         )
      )
 );

$posts_array = get_posts( $args );

     foreach ($posts_array as $value) {
        $cattest = $term->name;
        echo '<p><a href="/category/case-stuides/' .$term->slug. '">' .$term->name. '</a></p>';
        }       
      }
                                
?>

See screenshot below which shows exactly what is happening in the list of category names.

enter image description here

I've tried using array_unique but it doesn't work unless I am doing soemthing wrong or putting it in the wrong place, I appreciate any help with this.


Solution

  • You can use array_unique before getting the items (names), and before foreach

    <?php
    $items = array("Marketing", "NHS", "Nhs", "Science");
    
    $unique_items = array_map(function($item) {
        return strlen($item) == 3 ? strtoupper($item) : strtolower($item);
    }, array_unique(array_map('strtolower', $items)));
    
    $unique_items = array_map('ucfirst', $unique_items);
    
    print_r($unique_items); // ["Marketing", "NHS", "Science"]