Create a gist now

Instantly share code, notes, and snippets.

@umakantp /global.php
Last active Dec 31, 2015

What would you like to do?
Global functions: handy global function for any PHP project http://umakantpatil.com/posts/global-functions-handy-for-any-php-project
<?php
/**
* Global functions.
*/
/**
* Returns true if $var is not null.
*
* Useful in array_filter and other areas without involving anonymous
* functions (which phpcs throws a fit over all too often).
*
* @param mixed $var Variable to check.
*
* @return boolean
*/
function notNull(&$var) {
return $var !== null;
}
/**
* Return true if the given array is associative, false if not.
*
* @param mixed $arr Array to inspect.
*
* @return boolean true = Associative array, false = not.
*/
function isAssoc($arr) {
if (!$arr || !is_array($arr)) {
return false;
}
$keys = array_keys($arr);
return array_keys($keys) !== $keys;
}
/**
* Return the variable if set, or $default if not.
*
* Because $var is passed by reference, this function will autovivify
* array indexes and object properties. If testing arrays, you
* probably want ifseta. If testing objects, you probably want ifseto.
*
* @param mixed $var Variable to inspect and possibly return.
* @param mixed $default Value to return if $var is not set.
*
* @return mixed $var or $default
*/
function ifsetor(&$var, $default = null) {
return ($var !== null) ? $var : $default;
}
/**
* Return the value at $offset in $array if set, or $default if not.
*
* @param mixed $array Array to inspect.
* @param mixed $offset Offset into $array.
* @param mixed $default Value to return if $array[$offset] is not set.
*
* @return mixed $array[$offset] or $default
*/
function ifseta($array, $offset, $default = null) {
return is_array($array) && isset($array[$offset]) ? $array[$offset] : $default;
}
/**
* Return the value of a property in an object if set, or $default if not.
*
* @param object $object Object to inspect.
* @param mixed $property Property on $object.
* @param mixed $default Value to return if $object->$property is not set.
*
* @return mixed $array[$offset] or $default
*/
function ifseto($object, $property, $default = null) {
return isset($object->$property) ? $object->$property : $default;
}
/**
* Return the value of a constant if set, or $default if not.
*
* @param string $constant Constant name.
* @param mixed $default Default value (optional).
*
* @return mixed Value of constant $constant or $default
*/
function ifdefor($constant, $default = null) {
return defined($constant) ? constant($constant) : $default;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment