PHPackages                             repat/php-helper - 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. [Database &amp; ORM](/categories/database)
4. /
5. repat/php-helper

ActiveLibrary[Database &amp; ORM](/categories/database)

repat/php-helper
================

Some helper function for developing applications with PHP 7.2+

0.1.22(3y ago)25.0k11MITPHPPHP &gt;=7.2

Since Aug 29Pushed 3y ago1 watchersCompare

[ Source](https://github.com/repat/php-helper)[ Packagist](https://packagist.org/packages/repat/php-helper)[ Docs](https://repat.de)[ RSS](/packages/repat-php-helper/feed)WikiDiscussions master Synced 3w ago

READMEChangelog (10)Dependencies (4)Versions (23)Used By (1)

php-helper
==========

[](#php-helper)

[![Latest Version on Packagist](https://camo.githubusercontent.com/540f928ad1419de93347bbc4ebdd0e8784072fb56ae2d27eda4fcf64de43c755/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f72657061742f7068702d68656c7065722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/repat/php-helper)[![Total Downloads](https://camo.githubusercontent.com/8e0437c7b51994b3fd8f6ecef23233b5ea0f1ae9e93d441d5f196dbfdc50cfdc/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f72657061742f7068702d68656c7065722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/repat/php-helper)

**php-helper** is a package full of helper functions I found useful when developing applications in PHP. All functions are wrapped with a `functions_exists()` in case of conflicts.

> ⚠️ Some of these functions used to be in `repat/laravel-helper`, which now has this package as a dependency.

Also have a look at

-
-
-
-

Ideas what should go in here? Write a pull request or email!

Installation
------------

[](#installation)

`$ composer require repat/php-helper`

Documentation
-------------

[](#documentation)

### Array

[](#array)

#### `array_equal($arr1, $arr2)`

[](#array_equalarr1-arr2)

Determines if 2 arrays have the same items, independent of order.

```
$arr1 = [1, 2, 3];
$arr2 = [3, 2, 1];

array_equal($arr1, $arr2);
// returns: true

$arr3 = [4, 5, 6];
array_equal($arr1, $arr3);
// returns: false
```

#### `array_key2value($array)`

[](#array_key2valuearray)

Returns an array where key == value. Syntactic sugar for `array_combine($array, $array);`

```
$array = [1, 3, 5];

print_r(array_key2value($array));
// returns: Array( [1] => 1, [3] => 3, [5] => 5 )
```

#### `array_delete_value($array, $value)`

[](#array_delete_valuearray-value)

Deletes all elements from `$array` that have value `$value`. Essentially syntactic sugar for `array_diff()`.

```
$array = ['foo', 'bar'];

print_r(array_delete_value($array, 'foo'));
// returns  Array( [1] => "bar" )
```

#### `contains_duplicates($array)`

[](#contains_duplicatesarray)

Checks if there are duplicates in given array.

```
contains_duplicates([1, 1]);
// returns: true
contains_duplicates([1, 2]);
// returns: false
```

#### `array_change_keys($array, $keys)`

[](#array_change_keysarray-keys)

Changes the keys recursively for an associative array. The second parameter is an array with the old key (of `$array`) as the key and the new key as the value.

```
$array = [
        'bar' => 'foo',
        'sub' => [
            'some' => 'thing',
        ],
];

$keys = [
    'bar' => 'biz', // change all 'bar' keys to 'biz' keys
    'some' => 'any',
];

array_change_keys($array, $keys);
// returns:[
//         'biz' => 'foo',
//         'sub' => [
//             'any' => 'thing',
//         ],
// ];
```

#### `array_key_replace($array, $oldKey, $newKey)`

[](#array_key_replacearray-oldkey-newkey)

Similar to `array_change_keys()` but it only works for one-dimensional arrays.

```
array_key_replace(['bar' => 'foo'], 'bar', 'bizz');
// returns : ['bizz' => 'foo']
```

#### `array_avg($array)`

[](#array_avgarray)

Calculates average (sum/amount) of values. Returns `null` if array is empty.

```
array_avg([1, 2, 3]);
// returns : 2

array_avg([]);
// returns : null
```

### Date

[](#date)

#### `days_in_month($month = null, $year = null)`

[](#days_in_monthmonth--null-year--null)

Returns amount of days in given month or year. Defaults to current month and year.

```
days_in_month();
// returns: 31 (for e.g. May)

days_in_month($april = 4);
// returns: 30

days_in_month($feb = 2, $year = 2020);
// returns: 29 (2020 is a leap year)
```

#### `days_this_month()`

[](#days_this_month)

Returns amount of days of the current month.

```
days_this_month();
// returns: 31 (for e.g. May)
```

#### `days_next_month()`

[](#days_next_month)

Returns amount of days of the next month.

```
days_next_month();
// returns: 30 (for e.g. May because June has 30)
```

#### `days_this_year()`

[](#days_this_year)

Returns amount of days of the current year.

```
days_this_year();
// returns: 365 (because it's not a leap year)
```

#### `days_left_in_month()`

[](#days_left_in_month)

Returns amount of days left in current month.

```
days_left_in_month();
// returns: 29 (on 1st April)
```

#### `days_left_in_year()`

[](#days_left_in_year)

Returns amount of days left in current year.

```
days_left_in_year();
// returns: 274 (on 1st April 2019)
```

#### `timezone_list()`

[](#timezone_list)

Returns a list of all timezones.

```
timezone_list();
// returns:
// [
// "Pacific/Pago_Pago" => "(UTC-11:00) Pacific/Pago_Pago",
// "Pacific/Niue" => "(UTC-11:00) Pacific/Niue",
// "Pacific/Midway" => "(UTC-11:00) Pacific/Midway",
// ...
// "Pacific/Chatham" => "(UTC+13:45) Pacific/Chatham",
// "Pacific/Kiritimati" => "(UTC+14:00) Pacific/Kiritimati",
// "Pacific/Apia" => "(UTC+14:00) Pacific/Apia",
// ];
```

#### `tomorrow()`

[](#tomorrow)

Similar to `today()` or `now()`, this function returns a Carbon instance for tomorrow.

```
tomorrow();
// returns: Carbon\Carbon @1554156000 {#5618
//     date: 2019-04-20 00:00:00.0 Europe/Amsterdam (+02:00),
//   }
```

#### `yesterday()`

[](#yesterday)

Similar to `today()` or `now()`, this function returns a Carbon instance for yesterday.

```
yesterday();
// returns: Carbon\Carbon @1554156000 {#5618
//     date: 2019-04-19 00:00:00.0 Europe/Amsterdam (+02:00),
//   }
```

#### `seconds2minutes($seconds)`

[](#seconds2minutesseconds)

Returns `i:s` string with 60+ minutes instead of showing the hours as well.

```
seconds2minutes(42);
// returns: 00:42

seconds2minutes(90);
// returns: 01:30

seconds2minutes(4223);
// returns: 70:23
```

#### `diff_in_days($start, $end)`

[](#diff_in_daysstart-end)

Uses Carbons `diffInDays()` and `parse()` methods to return the difference in days.

```
diff_in_days('2018-04-19', '2018-04-21');
// returns: 2

diff_in_days(today(), yesterday());
// returns: 1
```

### Object

[](#object)

#### `object2array($object)`

[](#object2arrayobject)

Array representation of an object, e.g. an Eloquent Model.

```
use App\Models\User;

object2array(User::first());
// returns: [
//      "casts" => [
//        "someday_at" => "datetime",
//       // ...
//      ],
//      "incrementing" => true,
//      "exists" => true,
//      "wasRecentlyCreated" => false,
//      "timestamps" => true,
// ]
```

#### `filepath2fqcn($filepath, $prefix = '')`

[](#filepath2fqcnfilepath-prefix--)

Will turn a filepath into a Fully Qualified Class Name.

```
filepath2fqcn('/Users/john/code/app/Models/User.php', '/Users/john/code/');
// returns: App\Models\User

filepath2fqcn('/Users/john/code/app/Models/User.php', '/Users/john/code');
// returns: App\Models\User

filepath2fqcn('app/Models/User.php');
// returns: App\Models\User

filepath2fqcn('/Users/john/code/app/Models/User.php');
// returns: \Users\john\code\app\Models\User
```

### Misc

[](#misc)

#### `toggle($switch)`

[](#toggleswitch)

If given `true`, returns `false` and vice-versa.

```
toggle(false);
// returns: true

toggle(true);
// returns: false
```

#### `generate_password($size = 15)`

[](#generate_passwordsize--15)

Returns a random password. Syntactic sugar for `str_random()`.

```
generate_password();
// returns: IZeJx3MeUdDhzE2
```

#### `auto_cast($value)`

[](#auto_castvalue)

Returns the value with the right type so e.g. you can compare type safe with `===`.

```
gettype(auto_cast('42'));
// returns: integer
gettype(auto_cast('42.0'));
// returns: double
gettype(auto_cast('true'));
// returns: boolean
```

#### `human_filesize($size)`

[](#human_filesizesize)

Returns a human readable form for given bytes. Goes up to [Yottabyte](https://en.wikipedia.org/wiki/Yottabyte).

```
human_filesize(4223);
// returns: 4.12kB
```

#### `permutations($array)`

[](#permutationsarray)

Returns a generator with all possible permutations of given array values.

Based on [eddiewoulds port](https://stackoverflow.com/a/43307800/2517690) port of [python code](https://docs.python.org/2/library/itertools.html#itertools.permutations).

```
$gen = permutations(['foo', 'bar', 'biz']);

iterator_to_array($gen)
// returns: [
   //   [
   //     "foo",
   //     "bar",
   //     "biz",
   //   ],
   //   [
   //     "foo",
   //     "biz",
   //     "bar",
   //   ],
   //   [
   //     "bar",
   //     "foo",
   //     "biz",
   //   ],
   //   [
   //     "bar",
   //     "biz",
   //     "foo",
   //   ],
   //   [
   //     "biz",
   //     "foo",
   //     "bar",
   //   ],
   //   [
   //     "biz",
   //     "bar",
   //     "foo",
   //   ],
   // ]
```

#### `zenith($type)`

[](#zenithtype)

Wrapper around magic numbers for the [Zenith](https://en.wikipedia.org/wiki/Zenith). The types can be:

- `astronomical`: 108.0
- `nautical`: 102.0
- `civil`: 96.0
- default: 90+50/60 (~90.83)

```
zenith('civil');
// returns: 96.0
```

#### `operating_system()`

[](#operating_system)

Returns on of the following constants (also see under constants):

- `macos`
- `windows`
- `linux`
- `bsd`

```
operating_system();
// returns: linux
LINUX
// returns: linux
```

#### `wikipedia($lemma, $lang = 'en', $return = '')`

[](#wikipedialemma-lang--en-return--)

Link URL to wikipedia for a certain language

```
wikipedia('Towel Day');
// returns: https://en.wikipedia.org/wiki/Towel_Day

wikipedia('Paris', 'fr', '#')
// returns: https://fr.wikipedia.org/wiki/Paris

wikipedia('Pariz', 'fr', '#')
// returns: #
```

#### `function_location($functionName)`

[](#function_locationfunctionname)

Uses [Reflection](https://www.php.net/manual/en/book.reflection.php) to return the location where the function was defined or `null` if function doesn't exist. Note that PHPs internal functions return a an empty string.

```
function_location('wikipedia')
// returns: /folder/on/drive/php-helper/src/misc_helper.php:198

function_location('function_does_not_exist')
// returns: null

function_location('array_map')
// returns: '' (empty string)
```

### Networking

[](#networking)

#### `scrub_url($url)`

[](#scrub_urlurl)

Removes the protocol, www and trailing slashes from a URL. You can then e.g. test HTTP vs. HTTPS connections.

```
scrub_url('https://www.repat.de/');
// returns: 'repat.de'

scrub_url('https://blog.fefe.de/?ts=a262bcdf');
// returns: 'blog.fefe.de/?ts=a262bcdf'
```

#### `http_status_code($url, $follow = true, $userAgent = null)`

[](#http_status_codeurl-follow--true-useragent--null)

Returns just the status code by sending an empty request with [curl](https://curl.haxx.se/). By default, it follows redirect so it will only return the last status code and not e.g. 301 Redirects. Disable following by setting the second parameter to `false`. Some sites require a User-Agent and then return another status code. A string can be passed to `$userAgent`. Requires `ext-curl`.

```
http_status_code('httpstat.us/500');
// returns: 500

http_status_code('http://repat.de'); // with 301 redirect to https://repat.de
// returns: 200

http_status_code('http://repat.de', false);
// returns: 301
```

#### `parse_signed_request($request, $clientSecret, $algo)`

[](#parse_signed_requestrequest-clientsecret-algo)

Parses a HMAC signed request. Copied from [Data Deletion Request Callback - Facebook for Developers](https://developers.facebook.com/docs/apps/delete-data). `$algo` defaults to `sha256`.

```
$requestString = null; // TODO
parse_signed_request($requestString, env('FACEBOOK_CLIENT_SECRET'));
```

#### `domain_slug($domain)`

[](#domain_slugdomain)

Validates a domain and creates a slug. Does not work for subdomains, see `sluggify_domain()` instead. Returns `null` on a parsing error.

```
domain_slug('blog.fefe.de')
//returns: blogfefede
domain_slug('blogfefe.de')
//returns: blogfefede
```

##### `gethostbyname6($domain)`

[](#gethostbyname6domain)

Returns a IPv6 address for given domain by using the DNS AAAA records. If none is found, the input domain is returned, much like `gethostbyname()` is doing for IPv4.

```
gethostbyname6('ipv4onlydomain.tld');

// returns: ipv4onlydomain.tld

gethostbyname6('example.com')

// returns: 2606:2800:220:1:248:1893:25c8:1946
```

##### `is_public_ip($ip)`

[](#is_public_ipip)

Returns if given IP is a public IPv4 or IPv6 address (vs. private or reserved)

```
is_public_ip('127.0.0.1'); // localhost

// returns: false

is_public_ip('::1/128'); // localhost

// returns: false

is_public_ip('192.168.1.42') // private network

// returns: false

$ipv4 = gethostbyname('example.com');
is_public_ip($ipv4);

// returns: true

$ipv6 = gethostbyname6('example.com');
is_public_ip($ipv6);

// returns true;
```

##### `final_redirect_target($url)`

[](#final_redirect_targeturl)

Follows all 301/302 redirects and returns the URL at the end of the chain, or `null`.

```
final_redirect_target('http://google.com');
// returns http://www.google.com
```

### String

[](#string)

#### `str_icontains($haystack, $needle)`

[](#str_icontainshaystack-needle)

Similar to [Str::contains()](https://laravel.com/docs/5.7/helpers#method-str-contains) but case *insensitive*.

```
str_icontains('FOOBAR', 'foo');
// returns: true

str_icontains('foobar', 'foo');
// returns: true

str_icontains('foobar', 'FOO');
// returns: true

str_icontains('foobar', 'test');
// returns: false
```

#### `to_ascii($string)`

[](#to_asciistring)

Removes all non [ASCII](https://en.wikipedia.org/wiki/ASCII) characters and returns the rest.

```
to_ascii('René');
// returns: Ren
```

#### `hyphen2_($string)`

[](#hyphen2_string)

Replaces all hyphen ("-") characters with underscore ("\_")

```
hyphen2_('foo-bar');
// returns: foo_bar
```

#### `_2hypen($string)`

[](#_2hypenstring)

Replaces all underscore ("\_") characters with hyphen ("-")

```
_2hypen('foo_bar');
// returns: foo-bar
```

#### `str_replace_once($search, $replace, $string)`

[](#str_replace_oncesearch-replace-string)

Same signature as `str_replace()`, but as name suggests, replaces only the first occurrence of `$search`.

```
str_replace_once('foo', 'bar', 'foofoo');
// returns: 'barfoo'
```

#### `title_case_wo_underscore($string)`

[](#title_case_wo_underscorestring)

[Title Case](https://en.wikipedia.org/wiki/Letter_case#Title_case) but without underscores.

```
title_case_wo_underscore('foo_bar');
// returns: Foo Bar

// vs.
// title_case('foo_bar')
// returns: Foo_Bar
```

#### `lorem_ipsum()`

[](#lorem_ipsum)

Returns an example of the [Lorem Ipsum](https://en.wikipedia.org/wiki/Lorem_ipsum) placeholder text.

```
lorem_ipsum();
// returns:
// Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
```

#### `sluggify_domain($domain)`

[](#sluggify_domaindomain)

Returns a slug version of the domain by exchanging full stops with underscores. `str_slug()` does not work with subdomains, as it removes full stops completely.

```
sluggify_domain('blog.fefe.de');
// returns: blog_fefe_de
str_slug('blog.fefe.de');
// returns: blogfefede

sluggify_domain('blogfefe.de');
// returns: blogfefe_de
str_slug('blogfefe.de');
// returns: blogfefede // same as subdomain on fefe.de
```

#### `str_remove($string, $remove)`

[](#str_removestring-remove)

Removes given string(s), numbers or array of strings. Syntactic sugar for `str_replace($remove, '', $string)`.

```
str_remove('foobar', 'bar');
// returns: foo
str_remove('foobar42', ['foo', 'bar']);
// returns: 42
str_remove('foobar42', 42);
// returns: foobar
```

#### `str_bytes($string)`

[](#str_bytesstring)

Returns the amount of bytes in a string.

```
str_bytes('foobar');
// returns: 6
str_bytes('fooßar');
// returns: 8
```

#### `regex_list($array)`

[](#regex_listarray)

Creates a string with regex for an OR separated list.

```
regex_list(['foo', 'bar', '42'])
// returns: \bfoo|\bbar|\b42
```

#### `base64_url_decode($url)`

[](#base64_url_decodeurl)

Decodes a base64-encoded URL. Copied from [Data Deletion Request Callback - Facebook for Developers](https://developers.facebook.com/docs/apps/delete-data)

```
base64_url_decode('aHR0cHM6Ly9yZXBhdC5kZQ==');
// returns: https://repat.de
```

#### `str_right($string, $until)`

[](#str_rightstring-until)

Syntactic sugar for [`str_after`](https://laravel.com/docs/5.8/helpers#method-str-after).

```
str_right('https://vimeo.com/165053513', '/');
// returns: 165053513
```

#### `str_left($string, $before)`

[](#str_leftstring-before)

Syntactic sugar for [`str_before`](https://laravel.com/docs/5.8/helpers#method-str-before).

```
str_left('https://vimeo.com/165053513', '165053513');
// returns: https://vimeo.com/
```

#### `normalize_nl($string)`

[](#normalize_nlstring)

Normalizes all new lines characters (`\r`, `\n`, `\r\n`) to the UNIX newline `\n`.

```
normalize_nl('foobar\r\n'); // Windows
// returns: foobar\n

normalize_nl('foobar\r'); // MacOS
// returns: foobar\n

normalize_nl('foobar\n'); // *nix
// returns: foobar\n
```

#### `str_count_upper($string)`

[](#str_count_upperstring)

Counts upper case characters in a string. See also `str_count_lower()`.

```
str_count_upper('FoObAr');
// returns: 3

str_count_upper('foobar');
// returns: 0

str_count_upper('FOOBAR');
// returns: 6
```

#### `str_count_lower($string)`

[](#str_count_lowerstring)

Counts lower case characters in a string. See also `str_count_upper()`.

```
str_count_lower('FoObAr');
// returns: 3

str_count_lower('foobar');
// returns: 6

str_count_lower('FOOBAR');
// returns: 0
```

#### `str_insert_bindings($sql, $bindings)`

[](#str_insert_bindingssql-bindings)

Inserts bindings for `?` characters in the SQL string. See also `insert_bindings()` of [`repat/laravel-helper`](https://packagist.org/packages/repat/laravel-helper).

```
str_insert_bindings('SELECT * FROM `table` WHERE id = ?', [42]);
// returns: SELECT * FROM `table` WHERE id = '42'
```

#### `contains_uppercase($string)`

[](#contains_uppercasestring)

If the given string contains at least one uppercase ASCII character.

```
contains_uppercase('Foobar');
// returns: true

contains_uppercase('foobar');
// returns: false

contains_uppercase('FOOBAR');
// returns: true
```

#### `contains_lowercase($string)`

[](#contains_lowercasestring)

If the given string contains at least one lowercase ASCII character.

```
contains_lowercase('Foobar');
// returns: true

contains_lowercase('foobar');
// returns: true

contains_lowercase('FOOBAR');
// returns: false
```

#### `contains_numbers($string)`

[](#contains_numbersstring)

If the given string (or number) contains at least one number.

```
contains_numbers('Foobar');
// returns: false

contains_numbers('Foobar42');
// returns: true

contains_numbers('42');
// returns: true

contains_numbers(42); // uses strval()
// returns: true
```

#### `country_name($iso, $locale)`

[](#country_nameiso-locale)

Converts [ISO Code 3166-1 alpha-2](https://en.wikipedia.org/wiki/List_of_ISO_3166_country_codes) `$iso` code into the full country name. Basically syntactic sugar for [`locale_get_display_region()`](https://www.php.net/manual/en/locale.getdisplayregion.php). Optionally accepts `$locale` to print the country name in a given language. `XK` will give you [Kosovo](https://en.wikipedia.org/wiki/International_recognition_of_Kosovo).

```
country_name('nz');
// returns: New Zealand

country_name('de');
// returns: Germany (Germany in English)

country_name('de', 'de');
// returns: Deutschland (Germany in German)
```

##### Wordpress

[](#wordpress)

These functions were pulled in from the [Open Source](https://en.wikipedia.org/wiki/Open-source_model) [Content Management System](https://en.wikipedia.org/wiki/Content_management_system) [Wordpress](https://wordpress.org), released under the [GPL 2](https://en.wikipedia.org/wiki/GNU_General_Public_License) (or later).

- `mbstring_binary_safe_encoding()`
- `reset_mbstring_encoding()`
- `seems_utf8()`

###### `remove_accents($string)`

[](#remove_accentsstring)

Removes special characters and replaces them with their ASCII counterparts

```
remove_accents('á');
// returns: a

remove_accents('René')
// returns: Rene
```

### Optional Packages

[](#optional-packages)

Optional packages suggested by this are required for these functions to work.

#### `markdown2html($markdown)`

[](#markdown2htmlmarkdown)

Uses [league/commonmark](https://commonmark.thephpleague.com/) to transform Markdown into HTML.

- `$ composer require league/commonmark`

```
markdown2html('# Header');
// returns: Header\n
```

#### `domain($url, $publicSuffixList)`

[](#domainurl-publicsuffixlist)

Uses [jeremykendall/php-domain-parser](https://github.com/jeremykendall/php-domain-parser) to return the domain only from a URL, removing protocol, subdomain (including *www*) and path. For that the package needs a public suffix list, which can be found at [publicsuffix.org](https://publicsuffix.org).

- `$ composer require jeremykendall/php-domain-parser`

```
// Don't use this code, it's just to illustrate where the file could be
$publicSuffixList = file_get_contents('https://publicsuffix.org/list/public_suffix_list.dat');
$path = '/tmp/public_suffix_list.dat';
file_put_contents($path, $publicSuffixList);

// ...

domain('https://repat.de/about?foo=bar', $path);
// returns: repat.de
```

### HTML

[](#html)

#### `linkify($string, $protocols = ['http', 'https', 'mail'], $attributes)`

[](#linkifystring-protocols--http-https-mail-attributes)

Returns the string with all URLs for given protocols made into links. Optionally, attributes for the [a tag](https://www.w3.org/TR/html4/struct/links.html) can be passed.

```
linkify('https://google.com is a search engine');
// returns: google.com is a search engine

linkify('https://google.com is a search engine', ['https'], ['target' => '_blank']);
// returns: google.com is a search engine
```

#### `embedded_video_url($url)`

[](#embedded_video_urlurl)

Returns the embedded version of a given [YouTube](https://youtube.com) or [Vimeo](https://vimeo.com) URL.

```
embedded_video_url('https://www.youtube.com/watch?v=dQw4w9WgXcQ');
// returns: https://www.youtube.com/embed/dQw4w9WgXcQ

embedded_video_url('https://vimeo.com/50491748');
// returns: https://player.vimeo.com/video/50491748
```

#### `ul_li_unpack($array, $separator)`

[](#ul_li_unpackarray-separator)

Unpacks an associated array into an [unordered list](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ul). Default separator is `:`.

```
ul_li_unpack(['foo' => 'bar']);
// returns: foo: bar

ul_li_unpack(['foo' => 'bar'], '=>');
// returns: foo=> bar
```

#### `contrast_color($bgColor)`

[](#contrast_colorbgcolor)

Uses the Luminosity Contrast algorithm to determine if white or black would be the best contrast color for a given hex background color.

Source: [tomloprod on stackoverflow](https://stackoverflow.com/a/42921358/2517690)

```
contrast_color('b9b6b6');
// returns: #000000

contrast_color('#496379');
// returns: #ffffff
```

### Flags

[](#flags)

#### `emoji_flag($iso)`

[](#emoji_flagiso)

Returns the emoji flag for a [ISO-3166 alpha-2](https://en.wikipedia.org/wiki/List_of_ISO_3166_country_codes) code, such as `nz` for *New Zealand* or `py` for *Paraguay*. Lowercase / Uppercase doesn't play a role. Will return a waving black flag for non existing country code (or rather, Unicode doesn't have a flag for it) or `null`. `XK` will give you the flag of [Kosovo](https://en.wikipedia.org/wiki/International_recognition_of_Kosovo).

```
emoji_flag('nz');
// returns: 🇳🇿

emoji_flag('PY');
// returns: 🇵🇾

emoji_flag(null);
// returns: 🏴
```

### Constants

[](#constants)

- `PARETO_HIGH`: 80
- `PARETO_LOW`: 20
- `MARIADB_DEFAULT_STRLEN`: 191
- `ONE_HUNDRED_PERCENT`: 100
- `KILO`: 1000
- `KIBI`: 1024
- `NBSP`: `\xc2\xa0`
- `CR`: `\r`
- `LF`: `\n`
- `CRLF`: `\r\n`
- `HTTP_1_0_VERBS`: \[get, head, post\]
- `HTTP_1_1_VERBS`: \[get, head, post, connect, delete, options, put, trace\]
- `HTTP_VERBS`: \[get, head, post, connect, delete, options, put, trace, patch\]
- `REGEX_WORD_BOUNDARY`: \\b
- `REGEX_FIRST_RESULT_KEY`: 1
- `REGEX_UPPERCASE_ASCII`: (A-Z)
- `REGEX_LOWERCASE_ASCII`: (a-z)
- `REGEX_NUMBERS`: (0-9)
- `REGEX_NEWLINES`: \\n|\\r\\n?
- `MACOS`: macos
- `WINDOWS`: windows
- `LINUX`: linux
- `BSD`: bsd
- `EXIT_SUCCESS`: 0
- `EXIT_FAILURE`: 1
- `HEX_RED`: #ff0000
- `HEX_GREEN`: #00ff00
- `HEX_BLUE`: #0000ff
- `HEX_WHITE`: #ffffff
- `HEX_BLACK`: #000000
- `WEAK_CIPHERS` : \[ TLS\_DHE\_RSA\_WITH\_AES\_256\_GCM\_SHA384, TLS\_DHE\_RSA\_WITH\_AES\_256\_CBC\_SHA256, TLS\_DHE\_RSA\_WITH\_AES\_256\_CBC\_SHA, TLS\_DHE\_RSA\_WITH\_CAMELLIA\_256\_CBC\_SHA, TLS\_DHE\_RSA\_WITH\_CAMELLIA\_128\_CBC\_SHA, TLS\_DHE\_RSA\_WITH\_AES\_128\_CBC\_SHA256, TLS\_DHE\_RSA\_WITH\_AES\_128\_CBC\_SHA, TLS\_DHE\_RSA\_WITH\_AES\_128\_GCM\_SHA256, TLS\_DHE\_RSA\_WITH\_3DES\_EDE\_CBC\_SHA, SSL\_DHE\_RSA\_WITH\_AES\_128\_CBC\_SHA, SSL\_DHE\_RSA\_WITH\_AES\_256\_CBC\_SHA, SSL\_DHE\_RSA\_WITH\_CAMELLIA\_256\_CBC\_SHA, SSL\_DHE\_RSA\_WITH\_CAMELLIA\_128\_CBC\_SHA, SSL\_DHE\_RSA\_WITH\_3DES\_EDE\_CBC\_SHA\]
- `INET_ADDRSTRLEN`: 16
- `INET6_ADDRSTRLEN`: 46

Contributors
------------

[](#contributors)

-

License
-------

[](#license)

- MIT, see [LICENSE](https://github.com/repat/php-helper/blob/master/LICENSE)

Version
-------

[](#version)

- Version 0.1.22

Contact
-------

[](#contact)

### repat

[](#repat)

- Homepage:
- e-mail:
- Twitter: [@repat123](https://twitter.com/repat123 "repat123 on twitter")

[![Flattr this git repo](https://camo.githubusercontent.com/7e3f46a36526479d701ef7f90a0f8c3ac2fbab3087446e2a9fceed75cd1ab802/687474703a2f2f6170692e666c617474722e636f6d2f627574746f6e2f666c617474722d62616467652d6c617267652e706e67)](https://flattr.com/submit/auto?user_id=repat&url=https://github.com/repat/php-helper&title=php-helper&language=&tags=github&category=software)

###  Health Score

29

—

LowBetter than 57% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity21

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity53

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% 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 ~58 days

Recently: every ~249 days

Total

22

Last Release

1268d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/405dab243007488e7e7851422e5864a9312aee36058d60f1e6d623232c4d3131?d=identicon)[repat](/maintainers/repat)

---

Top Contributors

[![repat](https://avatars.githubusercontent.com/u/516807?v=4)](https://github.com/repat "repat (27 commits)")

---

Tags

phphelperarraydatabasefilesstringsdate

### Embed Badge

![Health badge](/badges/repat-php-helper/health.svg)

```
[![Health](https://phpackages.com/badges/repat-php-helper/health.svg)](https://phpackages.com/packages/repat-php-helper)
```

###  Alternatives

[hyperf/database

A flexible database library.

192.9M293](/packages/hyperf-database)[mg-code/yii2-helpers

A collection of useful helper classes for Yii framework 2.0

2023.1k5](/packages/mg-code-yii2-helpers)[modul-is/orm

Lightweight hybrid ORM/Explorer

1118.7k](/packages/modul-is-orm)[jonas-elias/hyperf-oracle

A oracle handler for hyperf/database.

102.3k](/packages/jonas-elias-hyperf-oracle)

PHPackages © 2026

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