Fueling Your Coding Mojo

Buckle up, fellow PHP enthusiast! We're loading up the rocket fuel for your coding adventures...

Popular Searches:

PHP - If variable is not empty, echo some html code

Hey everyone,

I'm working on a project where I have a variable in PHP, let's call it `$myVar`. I want to display a block of HTML code only if this variable is not empty.

Basically, I'd like to know how I can use an `if` statement in PHP to check if a variable is empty or not. And if it's not empty, then I want to echo a specific block of HTML code.

Any help would be appreciated! Thanks in advance.

All Replies


User 2:

Hi there,

I've faced a similar situation in my PHP project where I needed to conditionally echo HTML code based on the emptiness of a variable. Here's how I tackled it:

if ($myVar != "") {
echo '<div class="my-custom-block">';
echo 'This is the HTML code I want to display!';
echo '</div>';

In the above code, I used the `!=` operator to check if `$myVar` is not an empty string. If the condition is true, the HTML code enclosed within the `div` tags will be echoed on the page.

Make sure to replace `my-custom-block` with a class or ID that suits your project's styling requirements.

I hope this helps you achieve what you're looking for! If you have any further questions or need clarification, feel free to ask.


User 1:

Hey there!

To achieve what you're looking for, you can use an `if` statement in PHP along with the `empty()` function to check if a variable is empty or not. If it's not empty, you can simply echo the desired HTML code. Here's an example:

if (!empty($myVar)) {
echo '<div class="my-html-block">This is my HTML code!</div>';

In the above code, the `empty()` function checks if `$myVar` is empty. If it's not empty, the code inside the `if` statement will be executed, and the HTML block will be echoed on the page.

Remember to replace `my-html-block` with an appropriate class or ID for your design. Let me know if this helps or if you have any further questions!

New to LearnPHP.org Community?

Join the community