Global functions: handy global functions for any PHP project

In my PHP projects, I use few global functions means can be used/accessed anywhere in the project. They are handy and reused a lot. Even you could be using them many times in a PHP program. Those are handy functions can be added easily in any project. No side effects, no library needed.. just pure functions.

Lets take an simple example, If you want to check if any key exists in array then take that value or lets keep default value null.

[php]$value = isset($arr[‘key’]) ? $arr[‘key’] : null;[/php]

Now you can see such code at many places in your PHP Project. Lets take an example of how we can write with the help of one of those handy functions which we will see ahead.

[php]$value = ifseta($arr, ‘key’);[/php]

Simple? ha!  What if you do not want default value as null but false?

[php]$value = ifseta($arr, ‘key’, false);[/php]

Makes life easy?

Let see what other functions we have with examples and then in the last gist for this functions.

notNull :- It returns true if given input is not null.
[php]if (notNull($check)) {[/php]

isAssoc:- Returns true if given array is associative.
[php] if (isAssoc($arr2)) { [/php]

ifsetor:- Returns the value of variable if set, or you could have default value to return.
[php] if (ifsetor($check)) { [/php]

ifseta:- Returns the value inside a offset in array if set, otherwise default value.
[php] $y = ifseta($arr, ‘key’); [/php]

ifseto:- Same as above, returns the value inside a property in object if set, otherwise default value.
[php] $y = ifseto($obj, ‘property’); [/php]

ifdefor:- Return the value of a constant if set, or default if not.
[php] $y = ifdefor(‘CONSTANT_HERE’); [/php]

Download the file or copy past the code in a file, name it global.php and include in your project.

Here is the gist link for functions:- https://gist.github.com/umakantp/61ec61c3a528164e237c

1 Comment

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.