Global functions: handy global functions for any PHP project
Every PHP developer has a handful of tiny snippets they find themselves typing over and over again. They aren’t complex, and they don’t justify pulling in a massive third-party library. They’re just pure, straightforward global functions that make daily coding a little more pleasant.
Over the years, I’ve packaged these into a single helpers.php (or global.php) file that I drop into almost every project I work on. They don’t have side effects, they require zero dependencies, and they save a massive amount of visual clutter.
Take a look at a standard check to see if an array key exists, falling back to null if it doesn’t. Historically, we’ve written it like this:
$value = isset($arr['key']) ? $arr['key'] : null;Instead of scattering variations of that ternary or isset block across hundreds of lines of code, I prefer wrapping it in a dedicated helper function. Look at how much cleaner this reads:
$value = ifseta($arr, 'key');(Update: Modern PHP gives us the null coalescing operator ??)
What if you want the default fallback to be false instead of null? Just pass it as the third argument:
$value = ifseta($arr, 'key', false);It’s a minor change, but scaled across a large application, it makes your code significantly easier to read at a glance.
Makes life easy?
The Helper Toolkit
Here are the six helper functions I use constantly, along with quick examples of how they clean up your logic:
1. notNull()
A quick readability win. Instead of writing !is_null($var), this lets you write exactly what you mean.
if (notNull($check)) {
// Proceed knowing the variable actually holds a value
}2. isAssoc()
PHP arrays are incredibly flexible, but sometimes you need to know if you’re dealing with a sequential list or a key-value associative dictionary.
if (isAssoc($arr2)) {
// Handle as an associative array
}3. ifsetor()
Returns a variable’s value if it’s set, or a custom default value if it isn’t.
$theme = ifsetor($userTheme, 'dark');4. ifseta()
Safely extracts a value from an array key without throwing “undefined index” notices.
$productId = ifseta($payload, 'id');5. ifseto()
The object equivalent of ifseta(). It safely grabs a property from an object if it exists, otherwise returning your default.
$metadata = ifseto($responseObj, 'meta');6. ifdefor()
Perfect for configuration files. It checks if a global constant has been defined and returns its value—otherwise, it falls back to a safe default.
$environment = ifdefor('APP_ENV', 'production');Grab the Code
You don’t need a composer package for this. Just copy the code, save it as global.php (or helpers.php), and require it at the entry point of your application.
I’ve hosted the full source code for these functions in a GitHub Gist so you can easily view, fork, or copy them into your next project:
Nice helper functions – thanks!