On of the things that I’ve enjoyed the most about working through the live workshop on WordPress plugin development is the conversation that’s ensued around writing WordPress code and PHP code readability in our Basecamp discussions.

For those of you who have been around a while, you know that I’m opinionated when it comes to writing WordPress code. Specifically, I believe that just because WordPress is written in PHP does not mean that we should forgo the APIs and use PHP functions just because we’re either more familiar with them or because we find them easier to use.

That said, there are times in which the native PHP functions are the way to go.

For example, string comparison.

PHP Code Readability: Strings

When it comes to detecting if a string is empty, or set, or if it exists, PHP offers a variety of functions that can be used to evaluate the value.

These functions include:

  • `empty`
  • `isset`
  • `strlen`
  • …and so on

The thing is, each of these functions actually lends themselves to a specific instance and I tend to lean in the direction that just because it works in a specific instance doesn’t mean that it’s the instance for which the function was intended.

Nonetheless, in the plugin that we’re building in the workshop, I have the following block of code:

if ( 0 < strlen ( $short_url ) ) {
    // The value exists, so do one thing
} else {
    // The value does not exist, so do something else
}

Easy enough, but I received a great question in the forums as to why I set my conditional up this way:

Why do you use this type of if check and not another?

`if ( 0 < strlen( $short_url ) ) { }`

Perhaps something like this?

`if( ! empty( $short_url) ) { }`

Again, I thought this was a good question because it demonstrates using another PHP function which can evaluate a string just as easy as another function.

But the reason that I’m a fan of using `strlen` to evaluate the length of the string is because PHP is not a strongly typed language, and using `strlen` explicitly shows that I’m intending to operate on a string.

For me, it’s an issue of PHP code readability.

Are There More Instances Like This?

I’m sure there are, and as I come across them I’ll likely be discussing them here. The thing is, we all have our own opinions and different styles for how we should be writing code.

This is just one such opinion, so feel free to share your own in the comments, as well.

Besides, I’d much rater learn how the rest of you guys are doing it, too.