All the missing php functions
Just run composer install [package_name]
After that all these functions should be available in every PHP file (via composer's autoloader)
Return data matching specific key value condition
function where(array $array = [], array $cond = [])
Example:
$match = where([['a'=>1],['b'=>2]], ['b'=>2]);
Returns the random version of array (original array is unchanged)
function randomize(array $array)
Returns same key from all items of a multi-dimensional array
function pluck(array $array, string $match)
Opposite of empty. Returns $value if not empty, otherwise false.
Great for if
loops. Also returns false if a hash has all empty values.
function not_empty($value)
Example:
$v = not_empty([]); // returns false
$v = not_empty(['a'=>'','b'=>'']); // returns false
$v = not_empty([1,2]); // returns [1,2]
Like array map but it's possible to change both keys and values (original array is unchanged)
function array_map_key_values($closure, $arr)
Example:
$v = array_map_key_values(function (&$k, &$v) { $k = "$k-a"; $v = "$v-3"; }, ['a' => 1, 'b' => 2, 'c' => 3]);
Calls array_map function with args
function array_map_args($fn, $array, ...$args)
Example:
$trim = array_map_args('ltrim', ['/test', '/best'], '/'); //passes '/' to ltrim
Sorts an array by any key
function sort_by_key($arr, $key, $descending = FALSE)
Example:
$v = sort_by_key([['name' => 'moe', 'age' => 40],['name' => 'larry', 'age' => 50],['name' => 'curly', 'age' => 60]], 'age', true);
Groups an array's item by any key
function group_by($arr, $match)
Example:
$v = group_by([['name' => 'maciej', 'continent' => 'Europe'],['name' => 'yoan', 'continent' => 'Europe'],['name' => 'brandtley', 'continent' => 'North America']], 'continent');
Breaks array into chunks
// → [[1, 2, 3], [4, 5]]
function chunk(array $array, $size = 1, $preserveKeys = FALSE)
Example:
$v = chunk([1, 2, 3, 4, 5], 3);
Set an array item using dot.path notation
function array_set(array &$arr, $path, $val)
Example:
$arr = []; array_set($arr, 'a.b.c.d', 11);
Gets an array item using dot.path notation
function array_get(array &$arr, $path, $default = NULL)
Example:
$v = array_get($arr, 'a.b.c.d', 'default');
Check if the all keys exist in the array (and are not empty)
Return value is hash with only keys
function has_keys($hash, ...$keys)
Returns only selected keys from a hash (including empty keys)
function pluck_keys($hash, ...$keys)
Returns only selected keys from a hash (ignores empty values)
function pluck_keys_ignore_empty($hash, ...$keys)
Check if an array is associative
function is_hash(array $arr)
Checks if the string is an email (returns $email if true otherwise false)
function is_email($email)
Checks if the string is a url (returns $url if true otherwise false)
function is_url($url)
Gets the first item of array or hash
@return array|string
function array_first($array, $reverse = FALSE)
Example:
$first = array_first([1,2,3]) => 1;
Get the last item of array or hash
function array_last($array)
Example:
$last = array_first([1,2,3], true) => 3;
Filters all array items by regex
function array_filter_regex($regex, $array)
Example:
$php = array_filter_regex('/\.php$/', $files);
Removes selected items from array / or keys from hash
function array_except(array $arr, ...$args)
Case in-sensitive in_array function
function in_array_nc($needle, $haystack)
Breaks string into array
function lines($str, $delim = '\r?\n')
Example:
$lines = lines("this\nis\n\na\r\ntest");
Convert multi-line text into a single line
function single_line($text, $delim = '')
Example:
$merge = single_line("this\nis\n\na\ntest", " - ");
Remove non-ansi characters from string
function ansi($str)
Creates a slugified version of a word or phrase
function slugify($text, $unique = FALSE)
Example:
$unique = slugify('this is a test', true = adds a number or increments existing number);
Generates a random password
function password($length = 16)
Inserts a string after a matching phrase in an existing string
function str_insert($document, $match, $insert, $ignore_case = FALSE, $replace = FALSE)
Replaces a block between matching tags with an existing string
function str_replace_block($document, $match_start, $match_end, $insert, $ignore_case = FALSE, $replace = FALSE)
Example:
$out = str_replace_block('data', '// ** start', '// ** end', 'new content', false, false);
Wraps a string inside characters (return '' if string is blank) - automatically determins the right char is NULL
function str_wrap($input, $left, $right = NULL, $wrap_blank = FALSE)
Example:
$str = str_wrap('test', "<", ">", true); => <test>, $str = str_wrap('ok', '"'); => "ok", $str = str_wrap('', '<b>'); => ''
Put quotes around a string (or items of an array)
function str_quote($input, $char = '"', $trim = TRUE)
Example:
$arr = str_quote([1, 'one ', '"two"']); //["1", "one", "two"]
Returns true if a string contains all the words
function str_match_all_words($str, array $words, $whole_words = TRUE, $ignore_case = TRUE, $order = FALSE)
Example:
$match = str_match_all_words('this is a test', ['/Th.s/i', 'a', 'test'], true, true, true); //order = words must be in order. Note: 1st word is regex, 2nd is a whole word.
Increase the version number by 1
function next_version($version)
Coverts any word into kebab-case
function kebab($input, $delim = '-')
Coverts any word to camelCase
function camel($string)
Converts text in camel/kebab/underscore case to normal text
function unslugify($slug, $ucwords = FALSE)
Returns any text inside parenthesis from a string
function remove_parens($string)
Example:
$str = remove_parens("Hustlin' ((Remix) Album Version (Explicit)) with (a(bbb(ccc)b)a) speed!");
Replaces any tags inside template
function template($str, $tags = [], $ignore_missing = FALSE)
Example:
$out = template('hi {{first}}, today is {{date}}', ['first' => 'san', 'date' => today()]);
Same as template, except it uses a file instead of string
function file_template($path, $tags = [])
Converts a string value to it's equivanelt boolean
function bool($str)
Evaluates a PHP string like include_once
function eval_php($code, $vars = [])
Example:
$result = eval_php('Hi <?php echo 1; ?>!', get_defined_vars()); //Hi 1!
Splits a sentence in tor words
function words($text)
Example:
$v = words('this is mr.san "hello" there!');
Splits a paragraph into sentences
function sentences($str)
Example:
$v = sentences('this is a test. hello dr.dre, how are you? ok, bye.');
Splits a name into first and last
function split_name($name, $default = 'Member')
Lists most common English stopwords
function stop_words()
Extracts an email address from text
function extract_email($text, $single = TRUE)
Convert name, email to "name"
function email_format($email, $name = '')
Converts html to text
function html2text($html, $extract_links = TRUE)
Gets the cookie value or returns $default using JSON format
function cookie_get_json($name, $default = [])
Sets a cookie in browser using JSON format
function cookie_set_json($name, $value, $expires = '+1 day', $append = FALSE, $domain = '')
Return the (sanitized) URL of current page
function self_uri($params = FALSE)
Appends the http part if not already present in uri
function absolute_uri($path, $host = '')
Appends new params at the end of existing URL
function url_append_params($url, $params = [])
Returns the name of file without extension
function file_name($path)
Example:
$name = file_name('c:/test.jpg'); //test
Returns the extension of file (without the dot)
function file_ext($path)
Example:
$ext = file_name('c:/test.jpg'); //jpg
Changes file extension (and optionally path)
function change_ext($path, $new_ext, $new_path = '')
Example:
$path = change_ext('c:/d/tmp.txt', 'mp3', [new_path]); # c:/d/tmp.mp3
Reads a file into an array
function file_arr($path)
Example:
$arr = file_arr('some.txt');
Reads a csv file (with header support)
function read_csv($path, $header = FALSE, $delim = ',')
Example:
$arr = read_csv('file', ['col1', 'col2'] | true = first line is header | false = no header);
Reads a json file (optionally returning a property using dot path notation)
function read_json($path, $prop = NULL, $default = NULL)
Example:
$prop = read_json('file'[, 'package.details.name', 'untitled'\);
Parses env file into a hash
function read_config($path, $name = NULL)
Reads a .env file into enviroment variables
function dot_env($path)
Writes to a file (optionally json_encoding any non-scalar data) and returns filename on success
function write_file($fn, $data, $append = FALSE)
Updates an existing json file setting (array of) properties using dot path notation
function write_json($path, array $props, $saveAs = NULL)
Example:
$result = write_json('file', ['package.details.name' => 'test', 'version' => 2][, 'save-as']); //true or false
JWT encodes a payload with $key
function jwt_encode($payload, $key = '')
Example:
$token = jwt_encode(['user_id' => 1][, 'secret' | env(APP_KEY)]);
JWT decodes a payload verifies it with $key
function jwt_decode($jwt, $key = '')
Example:
$result = jwt_decode('token'[, 'secret' | env(APP_KEY)]);
Converts everything to forward slashes
function unix_path($path)
Converts everything to back slashes
function dos_path($path)
Converts absolute path into relative path
function relative_path($docRoot, $path)
Example:
$relPath = relative_path('d:/songs', 'd:/songs/coldplay/amsterdam.txt');
Creates a temporary file with given extension and prefix
function temp_file($ext = 'tmp', $prefix = 'tmp')
Get [width, height] of images
function image_size($path)
Creates a thumbnail from any image
function make_thumb($src, $dest, $max_width = 100, $max_height = 100)
Get current users's home directory
function home_dir()
Returns all files in the directory
function directory($path, $depth = -1, $regex = NULL, $exclude = [], $sort = FALSE, $includeDirs = FALSE)
Example:
$files = directory('c:/tmp', depth [0 = no recursion, 1 = 1 level, -1 infinite], '/\.php$/' (optional regex for basename), [..dirs to exclude]);
@param SplFileInfo $file @param mixed $key @param RecursiveCallbackFilterIterator $iterator
@return bool True if you need to recurse or if the item is acceptable
function mime_type($fileName)
Performs a GET/POST request with $params using CURL
function curl($url, $method = 'get', $params = [], $headers = [], &$status = NULL)
Example:
$response = url_get('http://www.google.com/search', 'get', ['q' => 'test'] | json (post body), ['header1', 'header2'], &$status);
Saves data to Amazon S3
function upload($data, $fileName, $bucket, $mime = '', $acl = 'public-read')
Uploads a file to Amazon S3
function upload_file($file, $bucket, $path = '', $mime = '', $acl = 'public-read')
Lists the contents of a S3 bucket
function s3_contents($bucket, $path = '', $fileName = '/')
Example:
$list = s3_contents('bucket', 'dir'); // returns all files in dir, $file_data = s3_contents('bucket', '', 'path_to_file'); // returns file's data instead
@var \SimpleXMLElement $tag *
function decode_image_data($data, &$type = [])
Returns the gravatar url from email
function gravatar($email, $null_if_missing = FALSE)
Checks if the email address is disposable
function is_disposable_email($email, $mx_check = TRUE)
Returns data for a blank image
function blank_image($type = 'gif')
Example:
$data = blank_image('gif|png')
Uploads an image to imgur and return it's online URL
The following env vars must be defined: IMGUR_KEY
function imgur($path)
Creates a DOM document and returns it's xpath selector
For CSS selector: Use BrowserKit or pQuery! More here: https://stackoverflow.com/a/260609/1031454
function dom_path($html)
Example:
$xpath = dom_path(curl('http://www.example.com')); // foreach($xpath->query('//h1') as $node) print $node->textContent;
Downloads a file
function download($url, $file = NULL)
Example:
$file = download('http://www.bakalafoundation.org/wp/wp-content/uploads/2016/03/Google_logo_420_color_2x-1.png'[, 'c:/tmp/test.jpg']);
Send out an email using Amazon SES
The following keys must be defined: AWS_SECRET_ACCESS_KEY, AWS_ACCESS_KEY_ID
function email($to, $subject, $body, $attach = NULL)
Gets the domain from URL with or without sub-domain
function domain($url, $tld = TRUE)
Return fake user data from uinames.com
function fake_data()
Example:
$user = fake_data();
Return's today's date in dd-mm-yyyy format (utc)
function today($format = 'dd-mm-yyyy', $time = NULL)
Example:
$v = today('dd/mm/yy')
Coverts any date to Mysql format
function mysql_date($date = NULL)
Checks if debugging is enabled, i.e. global $debug var is set or DEBUG env is present
function is_debug()
Prints to STDERR
function debug(...$args)
Prints to STDERR with red color
function warning(...$args)
Logs error in ~/error.log
function log_error(...$args)
Get's the local IP address
function ip_address()
Return value of an environment variable
function env($name, $default = NULL)
Return the OS name (windows, mac, or linux)
function os()
Runs a command using system
cmd('curl -F "data=@%s" -F "userid=%d" http://example.com', '@{"json":"data"}', 3); will automatically save first argument to file and insert its path
function cmd(...$args)
Runs a process in the background
function bg(...$args)
Captures the output of command using backticks and trims the output
function cmd_capture(...$args)
Runs commands in parallel using xargs
function cmd_parallel(array $commands, int $max_parallel = 3)
Example:
$o = cmd_parallel(['youtube-dl 1', 'youtube-dl 2', 'php sleep.php'], 3);
Caches (read/write) value to memory
function cache_memory($key, $value = NULL)
Example:
$r = cache_memory('key', [1, 2]);
Caches (read/write) value to file cache
function cache_local($key, $value = NULL, $expires = 86400)
Example:
$r = cache_local('key', [1, 2], -86400); //fresh result - cache for 86400
Waits for confirmation from command line
function confirm($msg = 'Are you sure?', $default = 'y', $accept = '/^y/i')
Dumps variables to screen or browser (with proper formatting)
function dump(...$args)
Encrypts a string
function encrypt_str($string, $password = '')
Decrypts a string encoded with encrypt
function decrypt_str($string, $password = '')
Checks if PHP is running in CLI mode
function is_cli()
Gets an argument by name (or alias) from command line
@return mixed
function get_argv($name = NULL, $default = NULL)
Example:
$val = get_argv('name', null);
Shows or hides all errors
function show_errors($show = TRUE)