PHP Tips and Tricks

Messing around with PHP has honestly been one of the highlights of my dev life — picking up something new on every project, big or small.

Below are a handful of habits that helped me delete a surprising amount of boilerplate, plus a few that reshaped how I work altogether. Drop me a line if something sparks an idea or a question… and with that, let’s jump in.

Tip 1: (if and else)

This pattern shows up in tutorials everywhere, yet it deserves a closer look all the same. Reaching for else and else if isn’t wrong — they exist for a reason — but in certain spots they add nothing. Consider this:



function output_gender(bool $user_is_male) {
    if ($user_is_male) {
        return "User is male";
    } else {
        return "User is female";
    }
}


Here output_gender picks a fixed message depending on whether $user_is_male holds true. Once return fires inside a function, everything beneath it never runs — so when the flag is set, the trailing else is dead weight. Knowing that, we can drop the else entirely:



function output_gender(bool $user_is_male) {
    if ($user_is_male) {
        return "User is male";
    }

    return "User is female";
}


Since the condition comes back false, the if is skipped and execution falls straight through to the “User is female” line.

Tip 2: (if blocks: less vs more)

The next idea extends what we just covered, pushing it a little further. With an if/else — or with a setup like the one above — one branch, whether the if or the else, often holds far less code. In those cases, deal with the shorter branch first. A concrete example makes it click.



public function categoryWithPosts($category)
{
    $category = Category::find($category);

    if ($category) {
        $category->posts = $category->posts()->published()->get();
        return response(['data' => $category], 200);
    } else {
        return response(['error' => 'Category not found'], 404);
    }
}


That snippet looks up a post category, then branches on whether the lookup hit. If we applied ONLY the first tip, we would end up with this shape:



public function categoryWithPosts($category)
{
    $category = Category::find($category);

    if ($category) {
        $category->posts = $category->posts()->published()->get();
        // having any more code here would
        // bloat this part of the function
        return response(['data' => $category], 200);
    }

    return response(['error' => 'Category not found'], 404);
}


Nothing wrong with that version, except the important logic ends up nested inside {} and shoved one level deeper. Stretch this pattern over a longer method and the whole thing becomes awkward to hold in your head. Tip 2 suggests this instead:



public function categoryWithPosts($category)
{
    $category = Category::find($category);

    if (!$category) {
        return response(['error' => 'Category not found'], 404);
    }

    $category->posts = $category->posts()->published()->get();
    // we can freely have more code here
    // without worrying about the code looking weird
    return response(['data' => $category], 200);
}


Because the short branch is the failure path, we flip it with ! and bail out early — an “if not category, run code...” guard. The main logic then sits at the top level, free to grow.

Tip 3: (verifying multiple strings)

Say we need to know whether a variable matches any one of several strings — the naive route is a stack of conditions doing the checking:



$item = "candy";

switch ($item) {
    case 'candy':
        return true;
    case 'toy':
        return true;
    default:
        return false;
}
// we're not adding break because we're using return

// or
if ($item == 'candy' || $item == 'toy') {
    return true;
}

return false;


The above answers false whenever the value is neither candy nor toy. It works, but it repeats itself a lot. A tidier move is to stash the candidates in an array and search that:



if (in_array($item, ["candy", "toy"])) {
    return true;
}

return false;


That last one shrinks even more, since in_array already hands back a boolean.



return in_array($item, ["candy", "toy"]);


Several lines collapse into one — nice, isn’t it? The mechanism is simple: we keep the wanted strings in an array and feed it to in_array, which boils down to a check like:



if $item is inside the array holding "candy" and "toy", return true, else false


Fair question: why not simply compare $item against the two values inline? That’s one line too, after all:



return ($item == 'candy' || $item == 'toy');


Same outcome — until the list grows to, say, ten strings:



return ($letter == 'a' || $letter == 'b' || $letter == 'c' || $letter == 'd' ...);


That chain spirals out of control fast. The array form stays calm by comparison:



return in_array($letter, ["a", "b", "c", "d", ...]);


Heads-up: the value being tested goes in as the first argument of in_array

Tip 4: (??)

The ?? operator is arguably the quickest way to write a two-sided fallback on one line. Confused? One example will clear it up.



$data = [
    "a" => 1,
    "b" => 2,
    "c" => null,
];

return $data["c"] ? $data["c"] : "No data";


The final line checks the c key of $data: use it when truthy, otherwise fall back to “No data”.

The same line with ?? reads like this:



// ...
return $data["c"] ?? "No data";


Here ?? plays the part that || plays in other languages. A practical use looks like this:



$user = getUserFromDb($user_id) ?? trigger_error("User id is invalid");

echo $user;


getUserFromDb is meant to pull a user out of a database — but if nobody matches, we abort with trigger_error instead of assigning anything. Written longhand without ??, it becomes:



$user = getUserFromDb($user_id);

if (!$user) {
    trigger_error("User id is invalid");
}

echo $user;


Tip 5: (Recursiveness over repetition)

This one speaks for itself: reach for recursion instead of copy-pasted code. Some duplication is harmless, but when the same chunk keeps reappearing, turn it into a method that calls itself where it fits. A real example — a getter I wrote for my Leaf framework request object, which fetches one field (or several) from the incoming request:



/**
 * Returns request data
 *
 * This methods returns data passed into the request (request or form data).
 * This method returns get, post, put patch, delete or raw faw form data or NULL
 * if the data isn't found.
 *
 * @param string|array $params The parameter(s) to return
 * @param bool $safeData Sanitize output
 */


So the method accepts a string or an array, then answers with a single value or a collection accordingly. The straightforward version tests for an array, walks it, pulls each key, and looks a lot like this:



public function get($params, bool $safeData = true)
{
    if (is_string($params)) return $this->body($safeData)[$params] ?? null;

    $data = [];
    foreach ($params as $param) {
        $data[$param] = $this->body($safeData)[$params] ?? null;
    }
    return $data;
}


Notice the repeated $this->body($safeData)[$params] ?? null — and worse, a nested array would sail straight past this logic. Since this ships as a library, callers can throw anything at it, so I went recursive instead:



public function get($params, bool $safeData = true)
{
    if (is_string($params)) return $this->body($safeData)[$params] ?? null;

    $data = [];
    foreach ($params as $param) {
        $data[$param] = $this->get($param, $safeData); // I called the function again
    }
    return $data;
}


Now nothing is fetched until the current element is actually a string — a small change with real payoff. Keep in mind the method lives on a class, which is why $this shows up

Tip 6: (PHP + HTML)

For those moments you’re blending PHP with HTML — or the reverse 😅 — the default instinct looks like this:



<?php
foreach ($items as $item) {
    echo '
        <div class="product__card">
            <h3>{$item->name}</h3>
        </div>
    ';
}
?>


It runs, but all that HTML is trapped inside a string — and the bigger the markup grows, the harder it is to match tags or tell which part you’re editing. Luckily there’s a cleaner way.



<?php foreach ($items as $item): ?>
    <div class="product__card">
        <h3><?php echo $item->name; ?></h3>
    </div>
<?php endforeach; ?>


Indentation and markup survive intact — and no, that isn’t a templating engine, it’s plain PHP being helpful. Flexibility like this is PHP’s trademark: one job, many valid spellings. The snippet above leans on:



foreach (...):
// code
endforeach;

// also works with if
if (...):
// code
endif;

// also
if (...) #one line code

while():
// ...
endwhile;


Tip 7: (Writing functional blocks)

Those helpers can wrap anything from a full-blown feature down to a one-line alias for a built-in. Beyond killing repetition, they streamline your workflow and read better, too.

A redirect helper built that way looks like this:



function redirectTo($route) {
    header("location: $route", true, 302);
}


From then on, redirectTo("/home") reads far better than spelling out header("location: /home", true, 302) everywhere. The same thinking covers third-party SDK calls and drawn-out processes: expose one tidy, reusable entry point, for instance:



UserNotification::send($user_id, $notification);


— clearly nicer than pasting a dozen lines wherever a user needs notifying. Tiny habit, big win.

Tip 8: (Using Types)

One more plain-spoken one. Type declarations sit among PHP’s most underused — yet most protective — tools, and they spare whole teams (yourself included) a lot of grief.

Sure, doc comments like the one in tip 5 help, but hand-writing them for every function and variable across a big codebase quickly turns into a chore.

Here’s the kind of slow-burning bug that types prevent:



function getItem($item) {
    // $item is expected to be an array
    // for whatever reason
    return allItems()[$item[0]];
}


Come back to getItem in a few weeks — alone or with teammates — and the bare $item parameter tells you nothing. It looks like it wants a string, yet the body indexes it like an array.

The nasty part: handing it a string doesn’t crash outright. Ever wonder why not?

Pass "chair" and PHP happily resolves allItems()["c"] — a mystery error waiting to ruin a night 😅. One word fixes it:



function getItem(array $item) {
    return allItems()[$item[0]];
}


Now only the right type gets through the door. The PHP manual covers the rest in depth — worth a read over at php.net.

Runtime guards such as is_string and is_array — the same ones we used earlier — work as an alternative:



function getItem($item) {
    if (!is_array($item)) throwErr("item should be array");

    return allItems()[$item[0]];
}


Tip 9: (Frameworks/Libraries aren't evil)

Straight talk: third-party packages can bite. Every now and then a dependency creates more headaches than it solves. Before anyone accuses me of hating on open source — relax, I publish packages myself, so that’s hardly it!

The real advice: vet what you install. Skim the docs, scan the GitHub issues, and skip needless gambles. And circling back to Tip 7, wrap the features you borrow in your own thin layer. You keep more control, and the codebase stays tidy.

On frameworks, the old wisdom still holds: learn PHP itself first. Every PHP framework, whatever its flavor, leans on the language’s core habits and idioms, so fluency with vanilla PHP comes before anything else.

After that, settle on one stack you enjoy and commit to it. Plenty of solid options exist:

  • Laravel: maximal magic — it happily does almost everything unless you say otherwise
  • Slim: a REST API toolkit with a “bring your own pieces” feel
  • Leaf: my own project, borrowing from Slim and Laravel — magic, but the kind you can steer.

I’ve only listed frameworks I use day to day, so nobody can accuse me of bias.

Tip 10: (Don't just code!)

One last bonus, and it travels well beyond PHP. “Don’t just code” sounds odd, but the meaning is simple.

Picture a method that pulls a payout from someone’s balance. Dive straight into the implementation and sooner or later you’ll stall — scrolling back, re-checking another file, losing the thread.

My alternative? Sketch it out first:



// in class scope
public function requestPayout()
{
    // parse token to get user id

    // fetch user from DB with id

    // check if the user is eligible for payouts

    // get user balance with user helper

    // check and throwErr for insufficient funds

    // ...
}


That outline forces the thinking up front, before any real code exists. It also doubles as a checklist: every step of the process is already on the page, waiting to be verified.

Thanks for reading

That’s a wrap on the habits I’ve picked up writing PHP — take what clicks, leave what doesn’t, and build your own shortlist of favorites.

No single style owns the truth here, and PHP especially rewards experimentation, so if you’ve got a sharper approach, a missing trick, or a friendly disagreement, I’d love to hear it — just get in touch.

Get started with a consultation today.

Ready to discuss your project vision, an innovative idea, or a specific inquiry? I welcome your message. Click the button below to send an email and let's begin building something remarkable.

Send an E-mail