Add a space next to an echo in a loop – WordPress

How can I add space next to an echo of categories assigned to a post:

<?php  
   $category_detail=get_the_category($post->ID); 
   foreach($category_detail as $cd)
   { 
     echo $cd->slug; 
   }
?>

The above code prints all categories assigned to a post, but it prints it like this:

Read More
category1category5

how can I add a space between each category printed? ie category1 category5

Related posts

Leave a Reply

5 comments

  1. What is the logic behind the code is: we will test that if this is the first id to print or not. If this is the first id to print then we won’t do anything. But if it’s not the first id then we will print a space before printing it. That way every id will be separated by a single space and there will be no leading or trailing spaces.

    Code:

    <?php  
      $category_detail=get_the_category($post->ID); 
      $i = 0;
      foreach($category_detail as $cd)
      { 
       if($i)echo " ";
       echo $cd->slug;
       $i=1;
      }
    ?>
    
  2. Try this

    $count = 0;
    foreach($category_detail as $cd)
    {
       //if first item, don't append space, else append space
       echo ($count == 0 ? $cd->slug : ' '.$cd->slug);
       $count++;
    } ?>
    
  3. I usually do something simple like this:

    <?php  
       $category_detail=get_the_category($post->ID); 
       $sep='';
       foreach($category_detail as $cd)
       { 
         echo "${sep}".$cd->slug;
         $sep=' '; 
       }
    ?>
    

    No trailing or leading space.

  4. Here is another version using implode:

    $category_detail = get_the_category($post->ID);
    $category_slug_collect = array_map(
                                 function($obj) { return $obj->slug; }, 
                                 $category_detail
                             );
    echo implode($category_slug_collect, ' ');