PHP Echo If Examples

Glenn Glenn's Blog 0 Comments

There are a number of ways to echo PHP ‘If’ a statement is true. The most common syntax is:-


if (condition)
{
code to be executed if condition is true;
}

So something like:-


<?php
$yourtimevalue=date("H");
if ($yourtimevalue <"12")
  {
  echo "The hour time is less than 12";
  }
?>

The example will output if the current time (HOUR) is less than 12.

Echo HTML or PHP in PHP If Statement

We also like to use an alternate echo that allows you to inject PHP or HTML within the If Statement and this is useful in writing more complicated scripts. So something like:-


<?php if ($a == 5): ?>
A is equal to 5
<?php endif; ?>

With these basic building blocks you can advance the above snippet to something like:-


<?php if ($your_value == 'true'): ?>
<div>
<?php
// show and trim the wordpress excerpt
$my_excerpt = get_the_excerpt();
$trimmed_my_excerpt = wp_trim_words( $my_excerpt, $my_excerpt_length, '<a href="'. get_permalink() .'"> ...</a>' );
echo $trimmed_my_excerpt;
?>
</div>
<?php endif; ?>

We are using a version opt the above PHP If statement to create a custom Section for the awesome Pagelines DMS WordPress Framework. The script does the following:-

  1. Looks for a ‘true’ value (as opposed to ‘false’)
  2. Gathers the excerpt from the WordPress Post (custom posts etc)
  3. Trims the excerpt by a length specified by our ‘$my_excerpt_length’ (you can also use a numerical value here) and adds the permalink to the WordPress Post
  4. Echoes the trimmed excerpt

We hope you find this useful.

About the Author
PHP Echo If Examples PHP Echo If Examples 0da77002febbfe28d15144a57bbcc2c9 s 180 d mm r g

Glenn

A highly experienced WordPress Web Developer, Front-end and Back-end Developer & New Media Specialist with extensive knowledge of a wide spectrum of technologies in the Development and Creative Industries built up over a number of years.

Leave a Reply

Your email address will not be published. Required fields are marked *