Home > Blockchain >  PHP variable gets overwritten in foreeach loop with last item
PHP variable gets overwritten in foreeach loop with last item

Time:12-09

I've looked at other "PHP variable overwritten" answers and still can't figure this out.

I'm using this PHP to get all the product category slugs on a single product page:

global $post;
$terms = get_the_terms( $post->ID, 'product_cat' );
if(is_array($terms)){
foreach ($terms as $term) {
    $product_cat_slug = $term->slug;
    $product_cat_slugs = ' product_cat-' . $product_cat_slug;
    echo $product_cat_slugs;
}
}

The line echo $product_cat_slugs; outputs product_cat-category1 product_cat-category2.

The problem is that when I delete the echo $product_cat_slugs; from the function above and use <?php echo $product_cat_slugs; ?> elsewhere on the page, all I get for output is the last category slug product_cat-category2, and not both categories product_cat-category1 product_cat-category2.

What's wrong? $product_cat_slugs seems to be overwritten when outside the foreach; how can I prevent that?

How do I output product_cat-category1 product_cat-category2 outside of the loop?

CodePudding user response:

Might I suggest to append the string, such as

global $post;
$terms = get_the_terms( $post->ID, 'product_cat' );

if( is_array( $terms ) ) {
    $product_cat_slugs = ''; //Define the variable outside of the loop
    foreach ( $terms as $term ) {
        $product_cat_slugs .= ' product_cat-' . $term->slug; //Append the slug onto the string that already exists
    }
    echo $product_cat_slugs; //Echo the string outside of the loop so it only occurs once.
}
  • Related