PHP Programming Hacks That Will Make Your Life Easier

In PHP programming, just as in life there is often more than one way to skin a cat. Inexperienced programmers, and even certified PHP programmers often go about things the long way, oblivious to the fact that there’s a shortcut that will achieve the same result easier with less code. In this article we will take a look at a few programming hacks that will make your life easier.

Conditional Expressions

There are many short alternatives to using if statements in PHP. One of them is assigning a value to an array based on a certain condition. This could be done using a traditional “if” or even “switch” statement. However, there is an alternative way to do the same in one line.

In this example we check if a user has sufficient permissions to post on a blog. If not, an error is stored in the $errors array.

// Create a new user object and disallow making new posts on a blog.
$user = new stdClass();
$user->name = "John Doe";
$user->isAllowedToPost = false;
// Save all errors in an array if any occur.
$errors = [];
// Because the user is not allowed to post (the first condition results in false), the $errors array is populated with the first error that occurred.
$user->isAllowedToPost or $errors[] = "User not allowed to post here.";

You could continue the code by checking if the errors array has one or more errors in it. If it does, show an error message to the user telling that an error has occurred and the blog post was not submitted. Then you could loop through the array of errors with a foreach loop, displaying all the error descriptions in a list.

There are many more use cases for a conditional expression like this. You could for example use it in API calls. If the API is designed to return true when a call is successful, this could be a handy way to generate an error if an API call is unsuccessful. What is great about this technique is that you can do it all in a single line of code.

Special Variable Names

“A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores.” This is what the official PHP documentation has to say about variable names. While this is true, variable names are not limited to just these. Did you know it is possible to use dashes in variable names? Many other special characters (@, /, ! etc.) are supported too. All you have to do is to surround these special variables with curly brackets and quotation marks.

${'special-variable'} = "Now you can use dashes in variable names!";
echo ${'special-variable'};

Converting Arrays into Objects

Sometimes you may have to convert an array into a PHP object. There are multiple ways to achieve this, but the easiest way is to cast the array into an object.

$array = ["fruit1" => "banana", "fruit2" => "apple", "fruit3" => "orange"];
$object = (object)$array;
echo $object->fruit1;

Now that the array is converted into an object, $object->fruit1 prints out “banana” just as you might expect.

This may be useful if you want to use containers in a more object-oriented way. Now you can easily echo data inside a string without concatenating multiple strings together. Remember to use double quotes for this.

echo "The first fruit is $object->fruit1.";

Merging Arrays

Merging multiple separate arrays into one big array in PHP is often done with the built-in function array_merge(). However, there is an easier way to do it: using the addition operator (+).

$array1 = ["fruit1" => "banana", "fruit2" => "apple"];
$array2 = ["fruit3" => "orange", "fruit1" => "pear"];

$newArray = $array1 + $array2;
var_dump($newArray);

Keep in mind array_merge() and the addition operator are not identical in functionality. array_merge() overwrites duplicate array keys while the addition operator keeps the first occurrence of a key in the array. For example, in the above code we have defined ”fruit1” twice. When using the addition operator, the value of “fruit1” is “banana” because it was defined first. If you need this functionality in your code, use the addition operator to easily merge arrays together.

Variable Variables

“Variable variables” is a rarely used feature that you can use to create variables dynamically. In the example below, we create a new variable. The name of the variable depends on what is passed in as a POST request.

// Let's assume we pass in "user1_" in the post request and store this in the $prefix variable.
$prefix = $_POST["prefix"];
// Use variable variables to dynamically create a new variable.
${$prefix . "name"} = "John Doe";
// We can now use the variable like a normal variable.
echo $user1_name;

Remember to use quotes when creating the variable (put “name” in quotes) in the above example. It also works without quotes but produces an error of type E_NOTICE if you leave them out.
It is recommended to use variable variables sparingly because they often make code more difficult to read and more prone to errors.

Explicit Error Suppression

Error reporting can be globally disabled with the error_reporting() function. This will disable errors for everything on the document. If you want to explicitly ignore errors for a single function, you can use the @ symbol in front of the function or expression.
Let’s take a variable declaration from the previous example:

${$prefix . name} = "John Doe";

By default, this produces an E_NOTICE error. As a temporary workaround it is possible to add the @ symbol in front of the expression:

@${$prefix . name} = "John Doe";

Suppressing errors is not the best way to solve issues, but if you want to ignore a single error that is filling up your error logs, this might be an ideal temporary solution until you have time to fix the root cause of the issue.

Arrays in Input Fields

Here is another easy trick with arrays in PHP. You can automatically fill an array based on what checkboxes a user has checked in a form.
First create an HTML form that has checkboxes:






When the form is submitted, all checked items are sent via a GET or POST request as an array. For easy access to the selected items, we can save them in a variable. This is all you have to do to save the values of selected checkboxes:

$fruits = $_POST["fruits"];

Validation Filters

Email validation is a common task in PHP. Did you know there is a built-in filter for data validation in PHP? A function called filter_var() can be used to filter and validate many types of data, such as emails, IP addresses, MAC addresses and URLs.
The filter_var() returns the same data it has been given if the validation is successful. If the validation fails, it returns false. In the following example we validate an email address and print out the results.

$email = "[email protected]";
// This will return false because the email is not valid.
$valid = filter_var($email, FILTER_VALIDATE_EMAIL);
if($valid) {
echo "The email is valid.";
}
else {
// This will get echoed because filter_var() returned false.
echo "The email is NOT valid.";
}

So there you have it, a few hacks that you can add to your PHP programming arsenal for your next project…and the one after that. In PHP there’s almost always different ways to achieve the same result, so don’t rest on your laurels, keep learning how to.minimise excess code to become a better web developer.

Article by Michael Green
Founder of CancanIT, Michael Green, is an advanced web developer with over 16 years experience in the industry. CancanIT offer professional certification
for both front-end and back-end web development.

Subscribe to Static Shift's digital marketing blog

Get our latest truely useful digital marketing articles straight to your inbox

Comments

Leave a Reply

Be the First to Comment!

Notify of
avatar
wpDiscuz

Want More Bookings & Enquiries From Your Website?

Talk To Us

Recent Web Design Projects

A few web design projects that we've completed for our happy clients recently!

Praise From The Clients We've Worked With

Don't just take our word for it!

Just want to thank you and your team sooo much again for all your hard work and support in building our online ticketing system. It’s so different for me not feeling stressed about ticketing issues this year and it’s so much easier for the customers to use, and us to manage, so you really have done an amazing job! Also for keeping up the communication, I really appreciate it!

Miriam Cuffe Abbey Medieval Festival

We didn’t like sending people to a separate website to book our tours. The integration of the Rezdy booking system into our web design has been awesome!  

Dessray Colledge Brisbane Whale Watching

Redeveloping our custom, responsive website has been a smooth, reliable and successful venture working with Karl at Static Shift. The communication from Karl and Karen was regular, detailed and clear. The resulting website meets all expectations. The website is running smoothly and much more efficiently than our previous design and is a lot easier on our server resources (which was a big problem with our level of traffic). Karl has a can do attitude, which means that all custom changes that we wanted were implemented to achieve the result we were looking for. We would definitely recommend using Static Shift.

Tanya Burgess Baby Hints & Tips - Australia-wide

As my hubbie is a webmaster and I must say a bloody good one at that…I can confidently say the site is excellent…even he reckons it’s fabulous and he is a critical bugger!

Peter Power St Helens Chamber Of Commerce - Tasmania

I got everything that I expected and much much more! My subscriptions to the page have increased by 400%, my SEO is always increasing and the feedback that I receive from current clients and new clients is nothing but exceptional!

Adam Murphy Adam Murphy (Keynote Speaker) - Adelaide

The team got straight to work; their patience with our indecision about how we wanted the site to look was very appreciated, Karl often giving great advice on making the site as professional as possible. We are very grateful to have come across Static Shift, the team’s ongoing help and support has been fantastic, they are always quick to respond with any concerns or queries. Thanks Karl and the team for your ongoing support, you really have been great!

Petra Johnson Hooked On Bamboo - Queensland