Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
February 13, 2021 11:09 pm GMT

Write good PHP - string management

Working with strings is common in any language, but it's very easy to make it harder than it needs to be!

In PHP, it's very easy to work with strings, but it can be easier.

Let's dissect the below example of a common, but poor usage of strings in PHP:

$firstname = 'John';$lastname = 'Doe';$name = 'The user ' . $firstname . ' ' . $lastname . ' joined in ' . date('d/m/y') . '. Their birthday is ' . 32 - date('Y');
Enter fullscreen mode Exit fullscreen mode

This will output exactly what you expect, but wooow, that's ugly, isn't it? Inline calculations, multiple sets of concatenation, and it's longer than it needs to be.

Let's see a refactor and explain it:

$first_name = 'John';$last_name = 'Doe';$full_name = "{$first_name} {$last_name}";$join_date = date('d/m/y'); $birthday = 32 - date('Y'); $name = "The user {$full_name} joined in {$join_date}. Their birthday is {$birthday}";
Enter fullscreen mode Exit fullscreen mode

We see more code, but it is much more readable, right?

What have we done here?

  • We've broken the dynamic values down to assigned variables outside of the string.
  • We've used interpolation to avoid concatenation. Interpolation means we can avoid the dot concat syntax, and awkward strings and spaces - making the string much much easier to manage.
  • Reduced the length of the string as a result of interpolation

Thanks to the above points, our refactor is much easier to read, and a lot easier to understand and edit.

We have introduced more code, but generally, readability should come before length. For beginners, it can be easy to fall into the trap of wanting to write really complicated code, in as few lines as possible - while cool, and very fun, it can easily get out of hand!

This has been a simple example of string management in PHP, I hope you enjoyed!

In the next part of this series, I'll cover writing logical structures with the happy path.


Original Link: https://dev.to/joemoses33/write-good-php-string-management-4lok

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To