phputils / all
All the missing php functions
README
Just run composer install [package_name]
After that all these functions should be available in every PHP file (via composer's autoloader)
Array related
String related
File related
Internet related
Array related functions
where
Return data matching specific key value condition
function where(array $array = [], array $cond = [])
Example:
$match = where([['a'=>1],['b'=>2]], ['b'=>2]);
randomize
Returns the random version of array (original array is unchanged)
function randomize(array $array)
pluck
Returns same key from all items of a multi-dimensional array
function pluck(array $array, string $match)
not_empty
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]
array_map_key_values
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]);
array_map_args
Calls array_map function with args
function array_map_args($fn, $array, ...$args)
Example:
$trim = array_map_args('ltrim', ['/test', '/best'], '/'); //passes '/' to ltrim
sort_by_key
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);
group_by
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');
chunk
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);
array_set
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);
array_get
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');
json_decode_array
Converts string, object or stdClass into an array ($preserve = true, leave empty objects "{}" as stdClass otherwise they convert to "[]")
function json_decode_array($obj, $preserve = TRUE)
has_keys
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)
pluck_keys
Returns only selected keys from a hash (including empty keys)
function pluck_keys($hash, ...$keys)
array_flatten
Flattens a multi-dimensional array
function array_flatten(array $array)
pluck_keys_ignore_empty
Returns only selected keys from a hash (ignores empty values)
function pluck_keys_ignore_empty($hash, ...$keys)
is_hash
Check if an array is associative
function is_hash(array $arr)
is_email
Checks if the string is an email (returns $email if true otherwise false)
function is_email($email)
is_phone
Checks if the string is a phone number (returns $phone if true otherwise false)
function is_phone($phone)
is_url
Checks if the string is a url (returns $url if true otherwise false)
function is_url($url)
array_first
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;
array_last
Get the last item of array or hash
function array_last($array)
Example:
$last = array_first([1,2,3], true) => 3;
array_filter_regex
Filters all array items by regex
function array_filter_regex($regex, $array)
Example:
$php = array_filter_regex('/\.php$/', $files);
array_except
Removes selected items from array / or keys from hash
function array_except(array $arr, ...$args)
in_array_nc
Case in-sensitive in_array function
function in_array_nc($needle, $haystack)
String related functions
lines
Breaks string into array
function lines($str, $delim = '\r?\n')
Example:
$lines = lines("this\nis\n\na\r\ntest");
single_line
Convert multi-line text into a single line
function single_line($text, $delim = '')
Example:
$merge = single_line("this\nis\n\na\ntest", " - ");
ansi
Remove non-ansi characters from string
function ansi($str)
slugify
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);
password
Generates a random password
function password($length = 16)
str_insert
Inserts a string after a matching phrase in an existing string
function str_insert($document, $match, $insert, $ignore_case = FALSE, $replace = FALSE)
str_replace_block
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);
str_wrap
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>'); => ''
str_quote
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"]
str_match_all_words
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.
str_match_brackets
Returns all the balanced matching brackets in the string
function str_match_brackets($str, $bracket = '
next_version
Increase the version number by 1
function next_version($version)
kebab
Coverts any word into kebab-case
function kebab($input, $delim = '-')
camel
Coverts any word to camelCase
function camel($string)
unslugify
Converts text in camel/kebab/underscore case to normal text
function unslugify($slug, $ucwords = FALSE)
remove_parens
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!");
template
Replaces any tags inside template
function template($str, $tags = [], $ignore_missing = FALSE)
Example:
$out = template('hi {{first}}, today is {{date}}', ['first' => 'san', 'date' => today()]);
file_template
Same as template, except it uses a file instead of string
function file_template($path, $tags = [])
bool
Converts a string value to it's equivanelt boolean
function bool($str)
eval_php
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!
words
Splits a sentence in tor words
function words($text)
Example:
$v = words('this is mr.san "hello" there!');
sentences
Splits a paragraph into sentences
function sentences($str)
Example:
$v = sentences('this is a test. hello dr.dre, how are you? ok, bye.');
split_name
Splits a name into first and last
function split_name($name, $default = 'Member')
stop_words
Lists most common English stopwords
function stop_words()
extract_email
Extracts an email address from text
function extract_email($text, $single = TRUE)
email_format
Convert name, email to "name"
function email_format($email, $name = '')
html2text
Converts html to text
function html2text($html, $extract_links = TRUE)
cookie_get_json
Gets the cookie value or returns $default using JSON format
function cookie_get_json($name, $default = [])
cookie_set_json
Sets a cookie in browser using JSON format
function cookie_set_json($name, $value, $expires = '+1 day', $append = FALSE, $domain = '')
self_uri
Return the (sanitized) URL of current page
function self_uri($params = FALSE)
absolute_uri
Appends the http part if not already present in uri
function absolute_uri($path, $host = '')
url_append_params
Appends new params at the end of existing URL
function url_append_params($url, $params = [])
file_name
Returns the name of file without extension
function file_name($path)
Example:
$name = file_name('c:/test.jpg'); //test
file_ext
Returns the extension of file (without the dot)
function file_ext($path)
Example:
$ext = file_name('c:/test.jpg'); //jpg
change_ext
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
file_arr
Reads a file into an array
function file_arr($path)
Example:
$arr = file_arr('some.txt');
File related functions
read_csv
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);
read_json
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'\);
fix_json
Converts a Javascript object into valid JSON
function fix_json($string, $fixNames = TRUE, $asArray = TRUE)
read_config
Parses env file into a hash
function read_config($path, $name = NULL)
dot_env
Reads a .env file into enviroment variables
function dot_env($path)
write_file
Writes to a file (optionally json_encoding any non-scalar data) and returns filename on success
function write_file($fn, $data, $append = FALSE)
write_json
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_encode
JWT encodes a payload with $key
function jwt_encode($payload, $key = '')
Example:
$token = jwt_encode(['user_id' => 1][, 'secret' | env(APP_KEY)]);
jwt_decode
JWT decodes a payload verifies it with $key
function jwt_decode($jwt, $key = '')
Example:
$result = jwt_decode('token'[, 'secret' | env(APP_KEY)]);
unix_path
Converts everything to forward slashes
function unix_path($path)
dos_path
Converts everything to back slashes
function dos_path($path)
relative_path
Converts absolute path into relative path
function relative_path($docRoot, $path)
Example:
$relPath = relative_path('d:/songs', 'd:/songs/coldplay/amsterdam.txt');
temp_file
Creates a temporary file with given extension and prefix
function temp_file($ext = 'tmp', $prefix = 'tmp')
image_size
Get [width, height] of images
function image_size($path)
placeholder_image
Returns a random placeholder image
function placeholder_image($width = 320, $height = 200, $type = 'any')
make_thumb
Creates a thumbnail from any image
function make_thumb($src, $dest, $max_width = 100, $max_height = 100)
home_dir
Get current users's home directory
function home_dir()
directory
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]);
deltree
@param SplFileInfo $file @param mixed $key @param RecursiveCallbackFilterIterator $iterator
@return bool True if you need to recurse or if the item is acceptable
function deltree($dir)
mime_type
Returns mime type of any file
function mime_type($fileName)
Example:
$mime = mime_type('test.jpg');
basename_url
Returns the last part of URL without query string
function basename_url($url)
Internet related functions
curl
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);
upload
Saves data to Amazon S3
function upload($data, $fileName, $bucket, $mime = '', $acl = 'public-read')
upload_file
Uploads a file to Amazon S3
function upload_file($file, $bucket, $path = '', $mime = '', $acl = 'public-read')
s3_contents
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
decode_image_data
@var \SimpleXMLElement $tag *
function decode_image_data($data, &$type = [])
gravatar
Returns the gravatar url from email
function gravatar($email, $null_if_missing = FALSE)
is_disposable_email
Checks if the email address is disposable
function is_disposable_email($email, $mx_check = TRUE)
blank_image
Returns data for a blank image
function blank_image($type = 'gif')
Example:
$data = blank_image('gif|png')
imgur
Uploads an image to imgur and return it's online URL
The following env vars must be defined: IMGUR_KEY
function imgur($path)
dom_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;
download
Downloads a file
function download($url, $file = NULL, $headers = [])
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)
domain
Gets the domain from URL with or without sub-domain
function domain($url, $tld = TRUE)
fake_data
Return fake user data from uinames.com
function fake_data()
Example:
$user = fake_data();
today
Other functions
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')
elapsed
Show number of seconds elapsed after $time
function elapsed($time, $now = NULL)
mysql_date
Coverts any date to Mysql format
function mysql_date($date = NULL)
is_debug
Checks if debugging is enabled, i.e. global $debug var is set or DEBUG env is present
function is_debug()
debug
Prints to STDERR
function debug(...$args)
warning
Prints to STDERR with red color
function warning(...$args)
app_dir
Return app's base dir
function app_dir($path = NULL, $check_exists = TRUE)
log_to_file
Write a line to log file
function log_to_file($file, ...$args)
log_error
Logs error in ~/error.log
function log_error(...$args)
ip_address
Get's the local IP address
function ip_address()
env
Return value of an environment variable
function env($name, $default = NULL)
os
Return the OS name (windows, mac, or linux)
function os()
cmd
Runs a command using system
- If any arg starts with a @ (or is not a scalar), it is saved in tmpfile and the file path is used instead
- If first arg is "false" then the command is dry-run
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)
bg
Runs a process in the background
function bg(...$args)
cmd_capture
Captures the output of command using backticks and trims the output
function cmd_capture(...$args)
cmd_parallel
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);
cache_memory
Caches (read/write) value to memory
function cache_memory($key, $value = NULL)
Example:
$r = cache_memory('key', [1, 2]);
cache_local
Caches (read/write) value to file cache
function cache_local($key, $value = NULL, $expires = 86400, $refresh = FALSE)
Example:
$r = cache_local('key', [1, 2], -86400, true); //fresh result - cache for 86400
confirm
Waits for confirmation from command line
function confirm($msg = 'Are you sure?', $default = 'y', $accept = '/^y/i')
dump
Dumps variables to screen or browser (with proper formatting)
function dump(...$args)
encrypt_str
Encrypts a string
function encrypt_str($string, $password = '')
decrypt_str
Decrypts a string encoded with encrypt
function decrypt_str($string, $password = '')
is_cli
Checks if PHP is running in CLI mode
function is_cli()
get_argv
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);
show_errors
Shows or hides all errors
function show_errors($show = TRUE)