DEV Community

Mateusz Jasiński
Mateusz Jasiński

Posted on


Nice tricks for PHP beginners

When we start our journey with programming, we don't really think about coding styles and best practices. We just copy style of our teachers/mentors

You know this mindset "It works. Don't touch it", but let's see how we can improve some of often-written lines, with much shorter and better-looking code

1. If-else statements

Let's take a look at this code

   return $results;
   return "Error 123";
Enter fullscreen mode Exit fullscreen mode

It works, but we see that we have 2 return statments, just diffrent values

So let's re-write it

return !empty($results) ? $results : "Error 123";
Enter fullscreen mode Exit fullscreen mode

Looks better, doesn't it?

Here we used ternary operator It's useful, especially when we assign value to variable, like this

   $role = is_admin($id) ? "Admin" : "User";
Enter fullscreen mode Exit fullscreen mode

Checking for null values

Ok, now we know how to simplify our if-else statement. So let's consider this scenario

We have login form with email, assigned to account, and some additional one, for security

With knowledge from last trick, our code looks like this:

$backupEmail = is_null($securityEmail) ? $securityEmail : $email;
Enter fullscreen mode Exit fullscreen mode

Quite nice, but we can still improve it using null coalescing operator
It's similar to ternary, but it checks, whether value is null

So, this is our code now

$backupEmail = $securityEmail ?? $email;
Enter fullscreen mode Exit fullscreen mode

And we have beautiful, simple code


2. Prepared statements

In today's back-end development with php, the safest method to run query's are prepared statements. For binding parameters to query, we often use bindParam function.

//some code...

$stmt = $db->prepare($sql);
$stmt->bindParam(":user",$user , PDO::PARAM_STR);
Enter fullscreen mode Exit fullscreen mode

But here are some problems with it

  • It requires to pass a variable
  • If we have multiple variables to pass to the query, we must use bindParam a lot, which makes mess in our code

Let's take a look into docs, more specifically, execute method parameters

An array of values with as many elements as there are bound parameters in the SQL statement being executed. All values are treated as PDO::PARAM_STR.

So we don't have to add new variables and binds!
Let's re-write it

$stmt = $db->prepare($sql);

Enter fullscreen mode Exit fullscreen mode

It may not make a big difference here but if we want to have some constant parameter, this method looks better and is faster to write

But it works, if we label parameters like in this query

 SELECT * FROM `users` WHERE `nickname` = ?
Enter fullscreen mode Exit fullscreen mode

But for this one, not really

 SELECT * FROM `users` WHERE `nickname` = :user
Enter fullscreen mode Exit fullscreen mode

So, how to fix it? Using associative arrays!

$stmt = $db->prepare($sql);
Enter fullscreen mode Exit fullscreen mode

Now everything works fine.

3. match() function

In php 8.0 creators added a cool alternative for switch case, match() function

The advantage of match over switch-case is comparison method. Switch compares values using loose comparison (==), but in match we can see strict comparison (===), so in this code:

    case "5": echo "wrong"; break;
    case 5: echo "right"; break;

Enter fullscreen mode Exit fullscreen mode

where $age = 5, switch will match value for first case

but using match() like this

echo  match ($age) {
    "5" => "wrong",
    5 => "right"
Enter fullscreen mode Exit fullscreen mode

We will see "right" displayed in browser.


In this article I showed you

  • Ternary operator
  • Null coalescing operator
  • Passing binds for query as parameter for execute()
  • match() as an alternative for switch-case

I hope that this article helped you with writing better code.
You can always leave some feedback in the comments, I appreciate that

Top comments (3)

cubiclesocial profile image

The first code example is missing a closing parenthesis.

There is one good reason to not use the ternary operator too heavily: Debugging. If you know the code works, the ternary operator can certainly optimize its visual appearance, but it is hard to set a breakpoint or do an echo inside a ternary operator.

The single greatest tips/tricks for PHP I can give are to avoid being function call heavy and to use built-in keywords as much as possible. Function calls in PHP, whether in PHP core or PHP userland, are expensive and slow. The same is true of all interpreted languages like Javascript, Python, Ruby, etc. - not just PHP. Obviously, you'll want to actually accomplish real work and therefore need to call various functions to accomplish that work. However, doing the same thing in pure PHP userland that a built-in function already does is going to be many times slower than just calling the built-in function. So don't run out and re-implement PHP core functions within PHP userland.

As to keywords:

isset() and empty() are commonly used keywords that act like functions that have their own engine-level tokens (T_ISSET and T_EMPTY respectively). That is, they are built right into the core Zend engine instead of being separate function calls. As a result, they are many times faster than calling a normal function in PHP.

wizarddos profile image
Mateusz Jasiński

I see, typos should be fixed now

gbhorwood profile image
grant horwood

one of the things that i always liked about php is, as a language, it was never afraid of just stealing the good bits from other languages; jave, perl, c. for instance, pattern matching is lifted straight from scala's pattern matching.

12 Rarely Used Javascript APIs You Need

Practical examples of some unique Javascript APIs that beautifully demonstrate a practical use-case.