util::array_first(array $array)
Retrieve the first value from an array. Can be run on function callbacks, and it will not modify the pointer
of the source array unlike most other methods of doing this.
Usage:
util::array_first( ['a', 'b', 'c'] );
=> Returns 'a'
util::array_first_key(array $array)
Retrieve the first key from an array. Can be run on function callbacks, and it will not modify the pointer of
the source array unlike most other methods of doing this.
Usage:
util::array_first_key( $users );
=> Returns 'brandon'
util::array_flatten(array $array[, bool $preserve_keys = TRUE])
Flattens a multi-dimensional array into a one dimensional array
Usage:
util::array_flatten( [ 'a', 'b', [ 'c', 'd', 'e', [ 'f', 'g', [ [ [ [ 'h', 'i', 'j' ] ] ] ] ] ] ] );
=> Returns [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' ]
util::array_get($var[, mixed $default = NULL])
Retrieve a value from an array, or return a given default if the index isn't set
Usage:
util::array_get($_POST['action'], 'index');
=> If $_POST['action'] is set, returns its value, otherwise returns 'index'
util::array_get($_POST['action']['do'], 'index');
=> Returns the value of $_POST['action']['do'] or 'index'
util::array_last(array $array)
Retrieve the last value from an array. Can be run on function callbacks, and it will not modify the pointer
of the source array unlike most other methods of doing this.
Usage:
util::array_last( [ 'a', 'b', 'c'] );
=> Returns 'c'
util::array_last_key(array $array)
Retrieve the last key from an array. Can be run on function callbacks, and it will not modify the pointer of
the source array unlike most other methods of doing this.
Usage:
util::array_last_key( $users );
=> Returns 'zane'
util::array_map_deep(array $array, callable $callback[, bool $on_nonscalar = FALSE])
Returns an array containing all the elements of $array after applying the callback function to each one recursively.
Particularly useful for avoiding errors when calling functions that only accept scalar values on an array that could
contain nested arrays, such as $_GET or $_POST.
Usage:
util::array_map_deep($_POST, 'htmlentities');
=> Recursively escapes each scalar value in $_POST
util::array_map_deep($_POST, 'htmlentities', TRUE);
=> Recursively escapes each value in $_POST regardless of its type
util::array_pluck(array $array, string $field[, bool $preserve_keys, bool $remove_nomatches])
Replaces each value in an array with the specified field of the array or object that used to be the value. Very
useful when you have an array of objects or arrays from a database, and you only want one specific field. For
example, you want an array of emails from an array of users.
Usage:
util::array_pluck([['val' => 1], ['val' => 2], ['val' => 3]], 'val');
=> Returns [1, 2, 3]
util::array_pluck($users, 'email');
=> Returns an array of email addresses for each user
util::array_search_deep(array $array, mixed $search[, string $field = FALSE])
Allows you to search for a value in an array of arrays or an array of objects, and return the key of the value
that matches the search criteria. If $field is unspecified, the entire array/object is searched.
Usage:
util::array_search_deep($_POST, 'delete_post');
=> Might return 'do' if $_POST['do']['action'] = 'delete_post'
util::array_search_deep($users, 'rogue_coder', 'username');
=> Might return 5 if $users[5]->username = 'rogue_coder'
util::array_clean(array $array)
Remove all null/empty/false values from the given array.
Usage:
util::array_clean( array( 'a', 'b', '', null, false, 0) );
=> Returns array('a', 'b');
util::add_query_arg()
Adds one ore more query args to the query string of the current URL or a given URL
Usage:
util::add_query_arg( 'user', '5', '/admin/users?action=edit' );
=> Returns '/admin/users?action=edit&user=5'
util::add_query_arg( [ 'user' => 5, 'action' => 'edit' ], '/admin/users' );
=> Returns '/admin/users?user=5&action=edit'
util::get_current_url()
Returns the current URL with hostname
Usage:
util::get_current_url();
=> Returns 'http://brandonwamboldt.ca/utilphp/'
util::is_https()
Returns true if the current page is being loaded over https, false if it isn't
Usage:
util::is_https();
=> Returns false
util::http_build_url([mixed $url[, mixed $parts[, int $flags = HTTP_URL_REPLACE[, array &amo;$new_url]]]])
Pure PHP implementation/polyfill for http_build_url
which requires pecl_http to be installed.
Usage:
echo util::http_build_url("http://user@www.example.com/pub/index.php?a=b#files",
array(
"scheme" => "ftp",
"host" => "ftp.example.com",
"path" => "files/current/",
"query" => "a=c"
),
HTTP_URL_STRIP_AUTH | HTTP_URL_JOIN_PATH | HTTP_URL_JOIN_QUERY | HTTP_URL_STRIP_FRAGMENT
);
The above example will output:
ftp://ftp.example.com/pub/files/current/?a=c
util::is_https()
Returns true if the current page is being loaded over https, false if it isn't
Usage:
util::is_https();
=> Returns false
util::remove_query_arg( array|string $query_args[, string $url])
Removes one ore more query args from the query string of the current URL or a given URL
Usage:
util::remove_query_arg( 'action', '/admin/users?action=edit&user=5' );
=> Returns '/admin/users?user=5'
util::remove_query_arg( [ 'user', 'action'], '/admin/users?action=edit&user=5' );
=> Returns '/admin/users'
util::slugify(string $string[, string $separator = "-", bool $css_mode = FALSE])
Generate a string safe for use in URLs from any given string. Converts any accent characters
to their equivalent normal characters and converts any other non-alphanumeric characters to
dashes, then converts any sequence of two or more dashes to a single dash. This function
generates slugs safe for use as URLs, and if you pass TRUE as the second parameter, it will
create strings safe for use as CSS classes or IDs.
Usage:
util::slugify('This is a random --string with an Ãccent');
=> Returns 'this-is-a-random-string-with-an-accent'
util::slugify('Another String', '.');
=> Returns 'another.string'
util::htmlentities(string $string[, bool $preserve_encoded_entities = FALSE])
Executes htmlentities with ENT_QUOTES set by default. However, if you pass TRUE as
the second parameter, it will not re-encode entities that are already encoded.
Usage:
util::htmlentities('this string < this string', TRUE);
=> Returns 'this string < this string'
util::htmlspecialchars(string $string[, bool $preserve_encoded_entities = FALSE])
Executes htmlspecialchars with ENT_QUOTES set by default. However, if you pass TRUE as
the second parameter, it will not re-encode entities that are already encoded.
Usage:
util::htmlspecialchars('this string < this string', TRUE);
=> Returns 'this string < this string'
util::linkify(string $text)
Find's any URLs in the specified text and wraps them with HTML anchor tags
Usage:
util::linkify('this string has a link to http://www.google.com');
=> Returns 'this string has a link to <a href="http://www.google.com/">www.google.com</a>'
util::match_string(string $pattern, string $string[, bool $caseSensitive = true])
Check if a string matches a given pattern. You can use '*' as a wildcard character.
Usage:
util::match_string("test/*", "test/my/test");
=> Returns true
util::match_string("test/", "test/my/test");
=> Returns false
util::random_string(int $length[, bool $human_friendly = TRUE, bool $include_symbols = FALSE, bool $no_duplicate_chars = FALSE])
Generates a random string of the specified length. Human friendly mode
will exclude characters that can be confused with other characters, such
as 0 (zero) and O (capital o), 1 (one) and l (lowercase L).
Usage:
util::random_string(8);
=> Returns 'a6BiF4UW'
util::number_to_word(int|float $number)
Converts a number into its text equivalent. For example, 56 becomes fifty-six.
util::number_to_word(512.5);
=> Returns 'five hundred and twelve point five'
util::ordinal(int $number)
Returns the ordinal version of a number (appends th, st, nd, rd)
Usage:
util::ordinal(22);
=> Returns '22nd'
util::remove_accents(string $string)
Converts all accent characters to their ASCII equivalents
Usage:
util::remove_accents('Àccent');
=> Returns 'Accent'
util::secure_random_string(int $length)
Generate a random string of characters. Will attempt to use a secure source (openssl).
Usage:
util::secure_random_string(16);
=> Returns '5bB1RJH0cQhNjviT'
util::seems_utf8(string $string)
Checks to see if a given string is UTF-8 encoded/safe
Usage:
util::seems_utf8('This is some random string user input');
=> Returns true
util::safe_truncate(string $string, int $length[, string $append = '...'])
Truncate a string to a specified length without cutting a word off
Usage:
util::safe_truncate('The quick brown fox jumps over the lazy dog', 24);
=> Returns 'The quick brown fox...'
util::size_format(int $bytes[, int $decimals = 0])
Formats an integer as a human friendly size string, such as 4 KiB.
Usage:
util::size_format( 25151251, 2 );
=> Returns '23.99 MiB'
util::str_to_bool(string $string)
Converts a string to boolean, looking for yes/no words like 'yes', 'no', 'true', 'false', 'y', 'n', etc
Usage:
util::str_to_bool('yes');
=> Returns true
util::zero_pad(int $number, int $length)
Pads a given number with zeroes on the left
Usage:
util::zero_pad(341, 8);
=> Returns '00000341'
util::strip_space(string $string)
Strip all withspace from the given string
Usage:
util::strip_space(' The quick brown fox jumps over the lazy dog ');
=> Returns 'Thequickbrownfoxjumpsoverthelazydog'
util::sanitize_string(string $string)
Sanitize a string by performing the following operation :
- Remove accents
- Lower the string
- Remove punctuation characters
- Strip whitespaces
Usage:
util::sanitize_string(' Benoit! à New-York? j’ai perçu 1 % : Qu’as-tu "gagné" chez M. V. Noël? Dix francs.');
=> Returns 'benoitanewyorkjaipercu1quastugagnechezmvnoeldixfrancs'
util::is_serialized(mixed $data)
Checks to see if a given variable is a seralized data structure
Usage:
util::is_serialized( 'a:0:{}' );
=> Returns true
util::maybe_serialize(mixed $data)
Serialize data, if needed to store in plaintext (Arrays or objects)
Usage:
util::maybe_serialize( 5 );
=> Returns 5
util::maybe_serialize( array() );
=> Returns 'a:0:{}'
util::maybe_unserialize(mixed $data)
Unserialize data, if it's a serialized string
Usage:
util::maybe_unserialize(5);
=> Returns 5
util::maybe_unserialize("a:0:{}");
=> Returns array()
util::fix_broken_serialization(mixed $data)
Attempt to fix a broken serialization string (e.g. where string offsets are incorrect). Can fix
errors that frequently occur with mismatched character sets or higher-than-ASCII characters.
Usage:
util::fix_broken_serialization('a:1:{s:4:"test";s:4:"abc";}');
=> Returns 'a:1:{s:4:"test";s:3:"abc";}'
util::force_download(string $filename, string $content = FALSE)
Transmit headers that force a browser to display the download file dialog. Cross
browser compatible. Only fires if headers have not already been sent.
Usage:
util::force_download( 'export.csv', file_get_contents( 'securefile.csv' ) );
=> The user will be prompted to download the file
util::get_client_ip(bool $trust_proxy_headers = FALSE)
Returns the IP address of the client. Only enable $trust_proxy_headers if your server is behind a proxy
that sets the HTTP_CLIENT_IP and HTTP_X_FORWARDED_FOR headers.
Usage:
util::get_client_ip();
=> Returns '12.123.12.100'
util::get_gravatar(string $email, int $size = 32)
Return the URL to a user's gravatar
Usage:
util::get_gravatar('brandon.wamboldt@gmail.com');
=> Returns 'http://www.gravatar.com/avatar/46679faeb6780ecb1ea57527fdc66eb3?s=32'
util::human_time_diff(int $from, int $to = '', int $as_text = FALSE, string $suffix = ' ago')
Converts a unix timestamp to a relative time string, such as "3 days ago" or "2 weeks ago"
Usage:
util::human_time_diff(time() - 7400);
=> Returns '2 hours ago'
util::human_time_diff(time() - 7400, '', TRUE);
=> Returns 'two hours ago'
util::validate_email(string $possible_email)
Validate an email address
Usage:
util::validate_email( 'brandon.wamboldt@gmail.com' );
=> Returns true
util::validate_email( 'not an email' );
=> Returns false