Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only add item as needed in PHP array

Tags:

loops

php

I have bits of code I want to throw in to my site, and provisioned a space right after <body> using 'flairs' (divs) that sit outside the design. Here's the code:

//Add Flair Containers as needed
if($flairs>0){
  echo "<!--Flair Graphics (if needed)-->\n";
    while($fQty = --$flairs+1){ //-- subracts 1, +1 accounts for 1 being 0
       $flair = array($flair1, $flair2, $flair3);
        foreach($flair as $flairCode){
          echo "<div id=\"flair-".$fQty++."\">".$flairCode."</div>\n";
        };
    };
};

It prints correctly, where content = $flair1, $flair2, and so on.

<div id="flair-1">Content1</div>
<div id="flair-2">Content2</div>
<div id="flair-3">Content3</div>

But if $flair2/$flair3 is empty, it still prints a div. How can I fix this?

like image 226
Casey Dwayne Avatar asked May 17 '26 14:05

Casey Dwayne


1 Answers

Within your foreach loop you can check if the value is empty and continue (i.e. skip) to the next value if it is.

Like so:

if($flairs>0){
  echo "<!--Flair Graphics (if needed)-->\n";
    while($fQty = --$flairs+1){ //-- subracts 1, +1 accounts for 1 being 0
       $flair = array($flair1, $flair2, $flair3);
        foreach($flair as $flairCode){
          if (empty($flairCode)) continue;
          echo "<div id=\"flair-".$fQty++."\">".$flairCode."</div>\n";
        };
    };
};
like image 197
micflan Avatar answered May 19 '26 04:05

micflan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!