PHPackages                             jbzoo/utils - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [HTTP &amp; Networking](/categories/http)
4. /
5. jbzoo/utils

ActiveLibrary[HTTP &amp; Networking](/categories/http)

jbzoo/utils
===========

Collection of PHP functions, mini classes and snippets for everyday developer's routine life.

7.3.0(9mo ago)8311.6M↓42.4%7120MITPHPPHP ^8.2CI passing

Since Oct 21Pushed 9mo ago34 watchersCompare

[ Source](https://github.com/JBZoo/Utils)[ Packagist](https://packagist.org/packages/jbzoo/utils)[ RSS](/packages/jbzoo-utils/feed)WikiDiscussions master Synced 3d ago

READMEChangelog (10)Dependencies (3)Versions (90)Used By (20)

JBZoo / Utils
=============

[](#jbzoo--utils)

[![CI](https://github.com/JBZoo/Utils/actions/workflows/main.yml/badge.svg?branch=master)](https://github.com/JBZoo/Utils/actions/workflows/main.yml?query=branch%3Amaster) [![Coverage Status](https://camo.githubusercontent.com/104373c6acf42c5bba1b3b0014563d790daded0c0eaa5c3e45f2f84bad035332/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f6769746875622f4a425a6f6f2f5574696c732f62616467652e7376673f6272616e63683d6d6173746572)](https://coveralls.io/github/JBZoo/Utils?branch=master) [![Psalm Coverage](https://camo.githubusercontent.com/c685315a98a1eed58747275bcc301d81ca7244287b938761096e320bc2b34c23/68747470733a2f2f73686570686572642e6465762f6769746875622f4a425a6f6f2f5574696c732f636f7665726167652e737667)](https://shepherd.dev/github/JBZoo/Utils) [![Psalm Level](https://camo.githubusercontent.com/d2c1179e06e1858ca157d9269460f11ad7358f2446ab6e03218df8cf89cc6e97/68747470733a2f2f73686570686572642e6465762f6769746875622f4a425a6f6f2f5574696c732f6c6576656c2e737667)](https://shepherd.dev/github/JBZoo/Utils) [![CodeFactor](https://camo.githubusercontent.com/051a3974a4f74fed1213063efa0f91f51bac1ceaaa01d14db1664258d3621c93/68747470733a2f2f7777772e636f6465666163746f722e696f2f7265706f7369746f72792f6769746875622f6a627a6f6f2f7574696c732f6261646765)](https://www.codefactor.io/repository/github/jbzoo/utils/issues)[![Stable Version](https://camo.githubusercontent.com/6f3c88179914c2675ce2e67b4f3e55ac90e8c3299e981dd900eb734a065aba4a/68747470733a2f2f706f7365722e707567782e6f72672f6a627a6f6f2f7574696c732f76657273696f6e)](https://packagist.org/packages/jbzoo/utils/) [![Total Downloads](https://camo.githubusercontent.com/2fc8b2f5f37c5fede67cdc41c4a0bf9a9643cd80a7a09a5b9faf45d82af34849/68747470733a2f2f706f7365722e707567782e6f72672f6a627a6f6f2f7574696c732f646f776e6c6f616473)](https://packagist.org/packages/jbzoo/utils/stats) [![Dependents](https://camo.githubusercontent.com/60d129ad70fb07802f1354c11e45ad4d54af5ada5c18a3805559dfb7e03e8e2e/68747470733a2f2f706f7365722e707567782e6f72672f6a627a6f6f2f7574696c732f646570656e64656e7473)](https://packagist.org/packages/jbzoo/utils/dependents?order_by=downloads) [![GitHub License](https://camo.githubusercontent.com/1bdd682fc52ca8bc13f8355b684e20d3021145c0b822bb1330f8a9de5b6f6eda/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f6a627a6f6f2f7574696c73)](https://github.com/JBZoo/Utils/blob/master/LICENSE)

- [Install](#install)
- [Usage](#usage)
    - [Smart functions](#smart-functions)
    - [JBZoo\\Utils\\Arr](#jbzooutilsarr)
    - [JBZoo\\Utils\\Cli](#jbzooutilscli)
    - [JBZoo\\Utils\\Csv](#jbzooutilscsv)
    - [JBZoo\\Utils\\Dates](#jbzooutilsdates)
    - [JBZoo\\Utils�mail](#jbzooutilsemail)
    - [JBZoo\\Utils�nv](#jbzooutilsenv)
    - [JBZoo\\Utils\\FS](#jbzooutilsfs)
    - [JBZoo\\Utils\\Filter](#jbzooutilsfilter)
    - [JBZoo\\Utils\\Http](#jbzooutilshttp)
    - [JBZoo\\Utils\\IP](#jbzooutilsip)
    - [JBZoo\\Utils\\Image](#jbzooutilsimage)
    - [JBZoo\\Utils\\PhpDocs](#jbzooutilsphpdocs)
    - [JBZoo\\Utils\\Ser](#jbzooutilsser)
    - [JBZoo\\Utils\\Slug](#jbzooutilsslug)
    - [JBZoo\\Utils\\Stats](#jbzooutilsstats)
    - [JBZoo\\Utils\\Str](#jbzooutilsstr)
    - [JBZoo\\Utils\\Sys](#jbzooutilssys)
    - [JBZoo\\Utils\\Timer](#jbzooutilstimer)
    - [JBZoo\\Utils\\Url](#jbzooutilsurl)
    - [JBZoo\\Utils\\Vars](#jbzooutilsvars)
    - [JBZoo\\Utils\\Xml](#jbzooutilsxml)
- [Links (ideas and some functions)](#links-ideas-and-some-functions)
- [Unit tests and check code style](#unit-tests-and-check-code-style)
- [License](#license)
- [See Also](#see-also)

Collection of PHP functions, mini classes and snippets for everyday developer's routine life.

Install
-------

[](#install)

```
composer require jbzoo/utils
```

Usage
-----

[](#usage)

### Smart functions

[](#smart-functions)

```
use function JBZoo\Utils\alias;
use function JBZoo\Utils\alpha;
use function JBZoo\Utils\alphanum;
use function JBZoo\Utils\bool;
use function JBZoo\Utils\digits;
use function JBZoo\Utils\float;
use function JBZoo\Utils\int;

int(' 10.0 ') === 10;
float(' 10.0 ') === 10.0;

bool(' yes ') === true;
bool(' no ') === false;
bool('1') === true;
bool('0') === false;

alias('Qwer ty') === 'qwer-ty';
digits('Qwer 1 ty2') === '12';
alpha('Qwer 1 ty2') === 'Qwerty';
alphanum(' #$% Qwer 1 ty2') === 'Qwer1ty2';
```

### JBZoo\\Utils\\Arr

[](#jbzooutilsarr)

```
Arr::addEachKey(array $array, string $prefix): array; // Add some prefix to each key.

Arr::clean(array $haystack): array; // Clean array by custom rule.

Arr::cleanBeforeJson(array $array): array; // Clean array before serialize to JSON.

Arr::first(array $array): ?mixed; // Returns the first element in an array.

Arr::firstKey(array $array): ?string|int|null; // Returns the first key in an array.

// Flatten a multi-dimensional array into a one dimensional array.
//                            overwrite keys from shallow nested arrays
Arr::flat(array $array, bool $preserveKeys = true): array;

Arr::getField(array $arrayList, string $fieldName = 'id'): array; // Get one field from array of arrays (array of objects).

Arr::getSchema(array $array): array; // Returns type of variables as array schema.

Arr::groupByKey(array $arrayList, string $key = 'id'): array; // Group array by key and return list of grouped values.

Arr::implode(string $glue, array $array): string; // Array imploding for nested array.

Arr::in(?mixed $value, array $array, bool $returnKey = false): ?string|int|bool|null; // Check is value exists in the array.

Arr::isAssoc(array $array): bool; // Check is array is type assoc.

Arr::key(?mixed $key, array $array, bool $returnValue = false): ?mixed; // Check if key exists.

Arr::last(array $array): ?mixed; // Returns the last element in an array.

Arr::lastKey(array $array): ?string|int|null; // Returns the last key in an array.

Arr::map(Closure $function, array $array): array; // Recursive array mapping.

// Returns an array containing all the elements of arr1 after applying
// the callback function to each one.
//                             (Objects, resources, etc)
Arr::mapDeep(array $array, callable $callback, bool $onNoScalar = false): array;

Arr::removeByValue(array $array, ?string|int|float|bool|null $value): array; // Remove all items from array by value.

// Searches for a given value in an array of arrays, objects and scalar values. You can optionally specify
// a field of the nested arrays and objects to search in.
Arr::search(array $array, ?string|int|float|bool|null $search, ??string $field = null): string|bool;

Arr::sortByArray(array $array, array $orderArray): array; // Sort an array by keys based on another array.

Arr::toComment(array $data): string; // Convert assoc array to comment style.

Arr::unique(array $array, bool $keepKeys = false): array; // Remove the duplicates from an array.

Arr::unshiftAssoc(array $array, string|int $key, ?mixed $value): array; // Add cell to the start of assoc array.

// Wraps its argument in an array unless it is already an array.
//   Arr.wrap(null)      # => []
//   Arr.wrap([1, 2, 3]) # => [1, 2, 3]
//   Arr.wrap(0)         # => [0]
Arr::wrap(?mixed $object): array;
```

### JBZoo\\Utils\\Cli

[](#jbzooutilscli)

```
Cli::build(string $command, array $args = []): string; // Build params for cli options.

Cli::check(): bool; // Is command line mode.

Cli::err(string $message, bool $addEol = true): bool; // Print line to std error.

Cli::exec(string $command, array $args = [], ??string $cwd = null, bool $verbose = false): string; // Execute cli commands.

Cli::getNumberOfColumns(): int; // Returns the number of columns of the terminal.

// Returns true if STDOUT supports colorization.
// This code has been copied and adapted from \Symfony\Component\Console\Output\OutputStream.
Cli::hasColorSupport(): bool;

Cli::isInteractive($fileDescriptor = 1): bool; // Returns if the file descriptor is an interactive terminal or not.

Cli::out(string $message, bool $addEol = true): bool; // Print line to std out.
```

### JBZoo\\Utils\\Csv

[](#jbzooutilscsv)

```
Csv::parse(string $csvFile, string $delimiter = ';', string $enclosure = '"', bool $hasHeader = true): array; // Simple parser for CSV files.
```

### JBZoo\\Utils\\Dates

[](#jbzooutilsdates)

```
Dates::factory(?mixed $time = null, ?DateTimeZone|string|null $timeZone = null): DateTime; // Build PHP \DateTime object from mixed input.

Dates::formatTime(float $seconds, int $minValuableSeconds = 2): string; // Convert seconds to human-readable format "H:i:s".

Dates::human(string|int $date, string $format = 'd M Y H:i'): string; // Convert date string ot unix timestamp to human-readable date format.

Dates::is(??string $date): bool; // Check if string is date.

Dates::isThisMonth(string|int $time): bool; // Returns true if date passed is within this month.

Dates::isThisWeek(string|int $time): bool; // Returns true if date passed is within this week.

Dates::isThisYear(string|int $time): bool; // Returns true if date passed is within this year.

Dates::isToday(string|int $time): bool; // Returns true if date passed is today.

Dates::isTomorrow(string|int $time): bool; // Returns true if date passed is tomorrow.

Dates::isYesterday(string|int $time): bool; // Returns true if date passed was yesterday.

Dates::sql(?string|int|null $time = null): string; // Convert time for sql format.

Dates::timezone(?DateTimeZone|string|null $timezone = null): DateTimeZone; // Returns a DateTimeZone object based on the current timezone.

Dates::toStamp(?DateTime|string|int|null $time = null, bool $currentIsDefault = true): int; // Convert to timestamp.
```

### JBZoo\\Utils\\Email

[](#jbzooutilsemail)

```
Email::check(?mixed $emails): array; // Check if email(s) is(are) valid. You can send one or an array of emails.

// Check for DNS MX records of the email domain.
// Notice that a (temporary) DNS error will have the same result as no records were found.
// Code coverage ignored because this method requires DNS requests that could not be reliable.
Email::checkDns(string $email): bool;

Email::getDomain(?mixed $emails): array; // Get domains from email addresses. The not valid email addresses will be skipped.

Email::getDomainSorted(array $emails): array; // Get domains from email addresses in alphabetical order.

Email::getGravatarBuiltInImages(): array; // Returns gravatar supported placeholders.

// Generates a Gravatar URL.
// Size of the image:
// * The default size is 32px, and it can be anywhere between 1px up to 2048px.
// * If requested any value above the allowed range, then the maximum is applied.
// * If requested any value bellow the minimum, then the default is applied.
// Default image:
// * It can be a URL to an image.
// * Or one of built-in options that Gravatar has. See Email::getGravatarBuiltInImages().
// * If none is defined then a built-in default is used. See Email::getGravatarBuiltInDefaultImage().
Email::getGravatarUrl(string $email, int $size = 32, string $defaultImage = 'identicon'): ??string;

Email::isValid(??string $email): bool; // Returns true if string has valid email format.

Email::random(int $userNameLength = 10): string; // Create random email.
```

### JBZoo\\Utils\\Env

[](#jbzooutilsenv)

```
Env::bool(string $envVarName, bool $default = false): bool; // Convert value of environment variable to strict bool value.

Env::convert(??string $value, int $options = 16): ?string|int|float|bool|null; // Converts the type of values like "true", "false", "null" or "123".

Env::float(string $envVarName, float $default = 0): float; // Convert value of environment variable to strict float value.

Env::get(string $envVarName, ?string|int|float|bool|null $default = null, int $options = 16): ?string|int|float|bool|null; // Returns an environment variable.

Env::int(string $envVarName, int $default = 0): int; // Convert value of environment variable to strict integer value.

Env::isExists(string $envVarName): bool; // Returns true if environment variable exists.

Env::string(string $envVarName, string $default = ''): string; // Convert value of environment variable to clean string.
```

### JBZoo\\Utils\\FS

[](#jbzooutilsfs)

```
FS::base(??string $path): string; // Returns name of file with ext from FS pathname.

FS::clean(??string $path, string $dirSep = '/'): string; // Function to strip trailing / or \ in a pathname.

FS::dirName(??string $path): string; // Returns name for directory from FS pathname.

FS::dirSize(string $dir): int; // Returns size of a given directory in bytes.

FS::executable(string $filename, bool $executable = true): bool; // Set the executable bit on a file to the minimum value that allows the user running PHP to read to it.

FS::ext(??string $path): string; // Returns extension of file from FS pathname.

FS::filename(??string $path): string; // Returns filename without ext from FS pathname.

FS::firstLine(string $filepath): ??string; // Quickest way for getting first file line.

FS::format(int $bytes, int $decimals = 2): string; // Nice formatting for computer sizes (Bytes).

FS::getRelative(string $path, ??string $rootPath = null, string $forceDS = '/'): string; // Find relative path of file (remove root part).

FS::isDir(??string $path): bool; // Check is current path directory.

FS::isFile(string $path): bool; // Check is current path regular file.

FS::isReal(??string $path): bool; // Returns clean realpath if file or directory exists.

FS::ls(string $dir): array; // Returns all paths inside a directory.

FS::openFile(string $filepath): ??string; // Binary safe to open file.

FS::perms(string $file, ??int $perms = null): string; // Returns the file permissions as a nice string, like -rw-r--r-- or false if the file is not found.

FS::readable(string $filename, bool $readable = true): bool; // Set the readable bit on a file to the minimum value that allows the user running PHP to read to it.

FS::real(??string $path): ??string; // Returns realpath (smart analog of PHP \realpath()).

// Removes a directory (and its contents) recursively.
// Contributed by Askar (ARACOOL) .
FS::rmDir(string $dir, bool $traverseSymlinks = true): bool;

FS::stripExt(string $path): string; // Strip off the extension if it exists.

FS::writable(string $filename, bool $writable = true): bool; // Set the writable bit on a file to the minimum value that allows the user running PHP to write to it.
```

### JBZoo\\Utils\\Filter

[](#jbzooutilsfilter)

```
Filter::_(?mixed $value, Closure|string $filters = 'raw'): ?mixed; // Apply custom filter to variable.

Filter::alias(string $string): string; // Get safe string for sensitive external dependencies.

Filter::alpha(??string $value): string; // Returns only alpha chars.

Filter::alphanum(??string $value): string; // Returns only alpha and digits chars.

Filter::arr(?mixed $value, ?Closure|string|null $filter = null): array; // Cleanup array. No empty values.

Filter::base64(string $value): string; // Returns only chars for base64.

Filter::bool(?mixed $variable): bool; // Converts many english words that equate to true or false to boolean.

Filter::className(string $input): string; // Convert words to PHP Class name.

Filter::clean(string $string): string; // Alias of "Str::clean($string, true, true)".

Filter::cmd(string $value): string; // Cleanup system command.

Filter::data(JBZoo\Data\Data|array $data): JBZoo\Data\Data; // Returns Data object from array.

Filter::digits(??string $value): string; // Returns only digits chars.

Filter::esc(string $string): string; // Alias of "Str::esc($string)".

Filter::float(?mixed $value, int $round = 10): float; // Smart converter string to float.

Filter::html(string $string): string; // Alias of "Str::htmlEnt($string)".

Filter::int(?string|int|float|bool|null $value): int; // Smart convert any string to int.

Filter::json(JBZoo\Data\JSON|array $data): JBZoo\Data\JSON; // Returns JSON object from array.

Filter::low(string $string): string; // String to lower and trim.

Filter::parseLines(array|string $input): array; // Parse lines to assoc list.

Filter::path(string $value): string; // Returns only chars for base64url.

Filter::raw(?mixed $variable): ?mixed; // RAW placeholder for internal API of the library.

Filter::strip(string $string): string; // Get safe string without html tags and trimmed.

Filter::stripQuotes(string $value): string; // Smart striping quotes, double and single.

Filter::stripSpace(string $string): string; // Alias of "Str::stripSpace($string)".

Filter::trim(string $value): string; // Alias for build-in function \trim().

Filter::trimExtend(string $value): string; // Extended trim function for remove all spaces, tabs, new lines and really special chars.

Filter::ucFirst(string $input): string; // First char to upper, other to lower.

Filter::up(string $string): string; // String to upper and trim.

Filter::xml(string $string): string; // Alias of "Xml::escape($string)".
```

### JBZoo\\Utils\\Http

[](#jbzooutilshttp)

```
// Transmit headers that force a browser to display the download file dialog.
// Cross browser compatible. Only fires if headers have not already been sent.
Http::download(string $filename): bool;

Http::getHeaders(): array; // Get all HTTP headers.

// Sets the headers to prevent caching for the different browsers.
// Different browsers support different nocache headers, so several
// headers must be sent so that all of them get the point that no caching should occur.
Http::nocache(): bool;

Http::utf8(string $contentType = 'text/html'): bool; // Transmit UTF-8 content headers if the headers haven't already been sent.
```

### JBZoo\\Utils\\IP

[](#jbzooutilsip)

```
IP::getNetMask(string $ipAddress): ??string; // Return network mask. For example, '192.0.0.0' => '255.255.255.0'.

// Returns the IP address of the client.
//                         ONLY use if your server is behind a proxy that sets these values
IP::getRemote(bool $trustProxy = false): string;

IP::v4InRange(string $ipAddress, string $range): bool; // Check if a given ip is in a network.
```

### JBZoo\\Utils\\Image

[](#jbzooutilsimage)

```
Image::addAlpha(GdImage $image, bool $isBlend = true): void; // Add alpha chanel to image resource.

Image::alpha(float $color): int; // Returns valid value of alpha-channel.

Image::blur(float $blur): int; // Return valid value to blur image (1-10).

Image::brightness(float $brightness): int; // Returns valid value to make image bright (-255..255).

Image::checkGD(bool $throwException = true): bool; // Check if GD library is enabled on server.

Image::color(float $color): int; // Returns valid value to change color segment of a image (0..255).

Image::colorize(float $colorize): int; // Returns valid value to change color segment of a image (-255..255).

Image::contrast(float $contrast): int; // Returns valid value to change contrast of a image (-100..100).

Image::direction(string $direction): string; // Returns valid value of image direction: 'x', 'y', 'xy', 'yx'.

Image::getInnerCoords(string $position, array $canvas, array $box, array $offset = []): ??array; // Determine position. Returns array with X and Y coordinates.

Image::imageCopyMergeAlpha(GdImage $dstImg, GdImage $srcImg, array $dist, array $src, array $srcSizes, int $opacity): void; // Same as PHP's imagecopymerge() function, except preserves alpha-transparency in 24-bit PNGs.

Image::isGif(??string $format = null): bool; // Checks if image has GIF format.

Image::isJpeg(??string $format = null): bool; // Checks if image has JPEG/JPG format.

Image::isPng(??string $format = null): bool; // Checks if image has PNG format.

Image::isSupportedFormat(string $format): bool; // Check is format supported by lib.

Image::isWebp(??string $format = null): bool; // Checks if image has WEBP format.

// Converts a hex color value to its RGB equivalent.
//                                 Where red, green, blue - integers 0-255, alpha - integer 0-127
Image::normalizeColor(array|string $origColor): array;

Image::opacity(float $opacity): int; // Check opacity value.

Image::opacity2Alpha(float $opacity): int; // Convert opacity value to alpha.

Image::percent(float $percent): int; // Return valid value of percent (0-100).

Image::position(string $position): string; // Check position name.

Image::quality(float $percent): int; // Returns valid value of image quality (0..100).

Image::rotate(float $color): int; // Returns valid value of image rotation (-360..360).

Image::smooth(float $smooth): int; // Returns valid value to change smoothness of a image (1..10).

Image::strToBin(string $imageString): ??string; // Convert string to binary data.
```

### JBZoo\\Utils\\PhpDocs

[](#jbzooutilsphpdocs)

```
// Simple parse of PHPDocs.
// Example or return value
//  [
//      'description' => 'Simple parse of PHPDocs. Example or return value',
//      'params'      => [
//          'param'  => ['string $phpDoc'],
//          'return' => ['array']
//      ]
//  ].
PhpDocs::parse(string $phpDoc): array;
```

### JBZoo\\Utils\\Ser

[](#jbzooutilsser)

```
// UnSerializes partially-corrupted arrays that occur sometimes. Addresses
// specifically the `unserialize(): Error at offset xxx of yyy bytes` error.
// NOTE: This error can *frequently* occur with mismatched character sets and higher-than-ASCII characters.
// Contributed by Theodore R. Smith of PHP Experts, Inc. .
Ser::fix(string $brokenSerializedData): string;

// Check value to find if it was serialized.
// If $data is not a string, then returned value will always be false. Serialized data is always a string.
Ser::is(?mixed $data): bool;

Ser::maybe(?mixed $data): ?mixed; // Serialize data, if needed.

Ser::maybeUn(string $data): ?mixed; // Unserialize value only if it is serialized.
```

### JBZoo\\Utils\\Slug

[](#jbzooutilsslug)

```
// Transliterates characters to their ASCII equivalents.
// Part of the URLify.php Project .
Slug::downCode(string $text, string $language = ''): 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.
Slug::filter(??string $string, string $separator = '-', bool $cssMode = false): string;

// Converts all accent characters to ASCII characters.
// If there are no accent characters, then the string given is just returned.
Slug::removeAccents(string $string, string $language = ''): string;

// Checks to see if a string is utf8 encoded.
// NOTE: This function checks for 5-Byte sequences, UTF8 has Bytes Sequences with a maximum length of 4.
// Written by Tony Ferrara .
Slug::seemsUTF8(string $string): bool;
```

### JBZoo\\Utils\\Stats

[](#jbzooutilsstats)

```
Stats::histogram(array $values, int $steps = 10, ??float $lowerBound = null, ??float $upperBound = null): array; // Generate a histogram. Note this is not a great function, and should not be relied upon for serious use.

Stats::linSpace(float $min, float $max, int $num = 50, bool $endpoint = true): array; // Returns an array populated with $num numbers from $min to $max.

Stats::mean(??array $values): float; // Returns the mean (average) value of the given values.

Stats::median(array $data): float; // Calculate the median of a given population.

Stats::percentile(array $data, int|float $percentile = 95): float; // Calculate the percentile of a given population.

Stats::renderAverage(array $values, int $rounding = 3): string; // Render human readable string of average value and system error.

Stats::renderMedian(array $values, int $rounding = 3): string; // Render human readable string of average value and system error.

Stats::stdDev(array $values, bool $sample = false): float; // Returns the standard deviation of a given population.

Stats::variance(array $values, bool $sample = false): float; // Returns the variance for a given population.
```

### JBZoo\\Utils\\Str

[](#jbzooutilsstr)

```
// Make string safe
// - Remove UTF-8 chars
// - Remove all tags
// - Trim
// - Add Slashes (opt)
// - To lower (opt).
Str::clean(string $string, bool $toLower = false, bool $addSlashes = false, bool $removeAccents = true): string;

Str::esc(string $string): string; // Escape UTF-8 strings.

// Escape string before save it as xml content.
// The function is moved. Please, use \JBZoo\Utils\Xml::escape($string). It'll be deprecated soon.
Str::escXml(string $string): string;

Str::getClassName(?object|string|null $object, bool $toLower = false): ??string; // Get class name without namespace.

Str::htmlEnt(string $string, bool $encodedEntities = false): string; // Convert >, = 7.0).
Sys::canCollectCodeCoverage(): bool;

// Returns the path to the binary of the current runtime.
// Appends ' --php' to the path when the runtime is HHVM.
Sys::getBinary(): string;

Sys::getDocRoot(): ??string; // Returns current document root.

Sys::getHome(): ??string; // Returns a home directory of current user.

Sys::getMemory(bool $isPeak = true): string; // Get usage memory, human-readable.

Sys::getName(): string; // Returns type of PHP.

Sys::getNameWithVersion(): string; // Return type and version of current PHP.

Sys::getUserName(): ??string; // Returns current linux user who runs script.

Sys::getVendorUrl(): string; // Return URL of PHP official web-site. It depends on PHP vendor.

Sys::getVersion(): ??string; // Returns current PHP version.

// Returns true when the runtime used is PHP with the PHPDBG SAPI
// and the phpdbg_*_oplog() functions are available (PHP >= 7.0).
Sys::hasPHPDBGCodeCoverage(): bool;

Sys::hasXdebug(): bool; // Returns true when the runtime used is PHP and Xdebug is loaded.

Sys::iniGet(string $varName): string; // Alias fo ini_get function.

Sys::iniSet(string $phpIniKey, string $newValue): bool; // Alias fo ini_set function.

Sys::isFunc(Closure|string $funcName): bool; // Checks if function exists and callable.

Sys::isHHVM(): bool; // Returns true when the runtime used is HHVM.

Sys::isPHP(string $version, string $current = '8.2.9'): bool; // Compares PHP versions.

Sys::isPHPDBG(): bool; // Returns true when the runtime used is PHP with the PHPDBG SAPI.

Sys::isRealPHP(): bool; // Returns true when the runtime used is PHP without the PHPDBG SAPI.

Sys::isRoot(): bool; // Check is current user ROOT.

Sys::isWin(): bool; // Check is current OS Windows.

Sys::setMemory(string $newLimit = '256M'): void; // Set new memory limit.

Sys::setTime(int $newLimit = 0): void; // Set PHP execution time limit (doesn't work in safe mode).
```

### JBZoo\\Utils\\Timer

[](#jbzooutilstimer)

```
Timer::format(float $milliSeconds): string; // Formats the elapsed time as a string.

Timer::formatMS(float $seconds): string; // Formats the elapsed time as a string.

Timer::getRequestTime(): float; // Get request time in microseconds.

Timer::timeSinceStart(): float; // Formats the elapsed time since the start of the request as a string.
```

### JBZoo\\Utils\\Url

[](#jbzooutilsurl)

```
Url::addArg(array $newParams, ??string $uri = null): string; // Add or remove query arguments to the URL.

Url::build(array $queryParams): string; // Builds HTTP query from array.

// Build a URL. The parts of the second URL will be merged into the first according to the flags' argument.
//                                or associative array like parse_url() returns
//                                would return
Url::buildAll(array|string $sourceUrl, array|string $destParts = [], int $flags = 1, array $newUrl = []): string;

Url::create(array $parts = []): string; // Create URL from array params.

Url::current(bool $addAuth = false): ??string; // Returns the current URL.

Url::delArg(array|string $keys, ??string $uri = null): string; // Removes an item or list from the query string.

Url::getAuth(): ??string; // Get current auth info.

Url::isAbsolute(string $path): bool; // Check if URL is not relative.

Url::isHttps(bool $trustProxyHeaders = false): bool; // Checks to see if the page is being server over SSL or not.

// Turns all the links in a string into HTML links.
// Part of the LinkifyURL Project .
Url::parseLink(string $text): string;

Url::path(): ??string; // Returns the current path.

Url::pathToRel(string $path): string; // Convert file path to relative URL.

Url::pathToUrl(string $path): string; // Convert file path to absolute URL.

Url::root(bool $addAuth = false): ??string; // Returns current root URL.
```

### JBZoo\\Utils\\Vars

[](#jbzooutilsvars)

```
Vars::isEven(int $number): bool; // Is the current value even?

Vars::isIn(float $number, float $min, float $max): bool; // Returns true if the number is within the min and max.

Vars::isNegative(float $number): bool; // Is the current value negative; less than zero.

Vars::isOdd(int $number): bool; // Is the current value odd?

Vars::isPositive(float $number, bool $zero = true): bool; // Is the current value positive; greater than or equal to zero.

Vars::limit(float $number, float $min, float $max): int; // Limits the number between two bounds.

Vars::max(float $number, float $max): int; // Decrease the number to the maximum if above threshold.

Vars::min(float $number, float $min): int; // Increase the number to the minimum if below threshold.

Vars::out(float $number, float $min, float $max): bool; // Returns true if the number is outside the min and max.

// Ensures $value is always within $min and $max range.
// If lower, $min is returned. If higher, $max is returned.
Vars::range(float $value, float $min, float $max): int;

Vars::relativePercent(float $normal, float $current): string; // Get relative percent.
```

### JBZoo\\Utils\\Xml

[](#jbzooutilsxml)

```
// Convert array to PHP DOMDocument object.
// Format of input array
// $source = [
//     '_node'     => '#document',
//     '_text'     => null,
//     '_cdata'    => null,
//     '_attrs'    => [],
//     '_children' => [
//         [
//             '_node'     => 'parent',
//             '_text'     => "Content of parent tag",
//             '_cdata'    => null,
//             '_attrs'    => ['parent-attribute' => 'value'],
//             '_children' => [
//                 [
//                     '_node'     => 'child',
//                     '_text'     => "Content of child tag",
//                     '_cdata'    => null,
//                     '_attrs'    => [],
//                     '_children' => [],
//                 ],
//             ]
//         ]
//     ]
// ];.
// Format of output
//
//     Content of parent tagContent of child tag
Xml::array2Dom(array $xmlAsArray, ??DOMElement $domElement = null, ??DOMDocument $document = null): DOMDocument;

Xml::createFromString(??string $source = null, bool $preserveWhiteSpace = false): DOMDocument; // Create DOMDocument object from XML-string.

// Convert PHP \DOMDocument or \DOMNode object to simple array
// Format of input XML (as string)
//
//     Content of parent tagContent of child tag.
// Format of output array
// $result = [
//     '_node'     => '#document',
//     '_text'     => null,
//     '_cdata'    => null,
//     '_attrs'    => [],
//     '_children' => [
//         [
//             '_node'     => 'parent',
//             '_text'     => "Content of parent tag",
//             '_cdata'    => null,
//             '_attrs'    => ['parent-attribute' => 'value'],
//             '_children' => [
//                 [
//                     '_node'     => 'child',
//                     '_text'     => "Content of child tag",
//                     '_cdata'    => null,
//                     '_attrs'    => [],
//                     '_children' => [],
//                 ],
//             ]
//         ]
//     ]
// ];
Xml::dom2Array(DOMNode $element): array;

Xml::escape(?string|int|float|null $rawXmlContent): string; // Escape string before save it as xml content.
```

Links (ideas and some functions)
--------------------------------

[](#links-ideas-and-some-functions)

- utilphp -
- PHPBinString -
- URLify for PHP -
- LinkifyURL Project
-
-
-
-
-
- Askar (ARACOOL)
- Sebastian Bergmann
- Sebastian Bergmann
- Oscar Otero

Unit tests and check code style
-------------------------------

[](#unit-tests-and-check-code-style)

```
make
make test-all
```

License
-------

[](#license)

MIT

See Also
--------

[](#see-also)

- [CI-Report-Converter](https://github.com/JBZoo/CI-Report-Converter) - Converting different error reports for deep compatibility with popular CI systems.
- [Composer-Diff](https://github.com/JBZoo/Composer-Diff) - See what packages have changed after `composer update`.
- [Composer-Graph](https://github.com/JBZoo/Composer-Graph) - Dependency graph visualization of composer.json based on mermaid-js.
- [Mermaid-PHP](https://github.com/JBZoo/Mermaid-PHP) - Generate diagrams and flowcharts with the help of the mermaid script language.
- [Image](https://github.com/JBZoo/Image) - Package provides object-oriented way to manipulate with images as simple as possible.
- [Data](https://github.com/JBZoo/Data) - Extended implementation of ArrayObject. Use files as config/array.
- [Retry](https://github.com/JBZoo/Retry) - Tiny PHP library providing retry/backoff functionality with multiple backoff strategies and jitter support.
- [SimpleTypes](https://github.com/JBZoo/SimpleTypes) - Converting any values and measures - money, weight, exchange rates, length, ...

###  Health Score

66

—

FairBetter than 99% of packages

Maintenance57

Moderate activity, may be stable

Popularity62

Solid adoption and visibility

Community37

Small or concentrated contributor base

Maturity91

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 93.5% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~41 days

Recently: every ~152 days

Total

89

Last Release

280d ago

Major Versions

1.7.11 → 2.0.02017-11-17

2.3.3 → 3.0.02019-11-24

3.1.2 → 4.0.02020-07-14

4.5.5 → 5.0.02022-06-05

5.0.0 → 7.0.02023-07-09

PHP version history (8 changes)1.0.0PHP &gt;=5.3.10

2.0.0PHP &gt;=7.1

2.1.0PHP &gt;=7.0

4.0.0PHP &gt;=7.2

4.0.2PHP ^7.2

5.0.0PHP &gt;=7.4

7.0.0PHP ^8.1

7.3.0PHP ^8.2

### Community

Maintainers

![](https://www.gravatar.com/avatar/75e6de2785f6d099699f430ff58404af4fc0e83060d2953028c9664a54704a5f?d=identicon)[smetdenis](/maintainers/smetdenis)

---

Top Contributors

[![SmetDenis](https://avatars.githubusercontent.com/u/1118678?v=4)](https://github.com/SmetDenis "SmetDenis (232 commits)")[![lfbn](https://avatars.githubusercontent.com/u/6152567?v=4)](https://github.com/lfbn "lfbn (8 commits)")[![hikouki](https://avatars.githubusercontent.com/u/15326035?v=4)](https://github.com/hikouki "hikouki (6 commits)")[![FooBarQuaxx](https://avatars.githubusercontent.com/u/2607178?v=4)](https://github.com/FooBarQuaxx "FooBarQuaxx (1 commits)")[![Phil-Venter](https://avatars.githubusercontent.com/u/13363810?v=4)](https://github.com/Phil-Venter "Phil-Venter (1 commits)")

---

Tags

array-manipulationsenviromentjbzoophpphp-functionssnippetsstring-manipulationutilitiesutilityutility-classesutility-functionutility-libraryutilsmbstringhttpurlslugifyclicommand-linefilesystemhelperarraystringutilityhelpersimageserializeemailenvironmenttimerfiltercollectionenvdatesutilsmisc

### Embed Badge

![Health badge](/badges/jbzoo-utils/health.svg)

```
[![Health](https://phpackages.com/badges/jbzoo-utils/health.svg)](https://phpackages.com/packages/jbzoo-utils)
```

###  Alternatives

[zbateson/mb-wrapper

Wrapper for mbstring with fallback to iconv for encoding conversion and string manipulation

4952.7M7](/packages/zbateson-mb-wrapper)[iteks/laravel-enum

A comprehensive Laravel package providing enhanced enum functionalities, including attribute handling, select array conversions, and fluent facade interactions for robust enum management in Laravel applications.

2519.3k](/packages/iteks-laravel-enum)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
