Giter Site home page Giter Site logo

php-functions's Introduction

Jasny's PHP functions

Build Status Code Coverage Scrutinizer Code Quality SensioLabsInsight

A set PHP functions that should have been part of PHP's core libraries.

Example

$found = str_contains($string, 'foo') && array_contains($array, ['all', 'of', 'these']);
// VS
$found = strpos($string, 'foo') !== false && count(array_intersect($array, ['all', 'of', 'these'])) === 3;

Installation

composer require jasny\php-functions

Usage

All functions are in the Jasny namespace.

use function Jasny\str_contains; // Import functions

str_contains('moonrise', 'on');

Jasny\slug('Foo bár'); // or use directly

To import all the functions to the global namespace require 'global.php' anywhere in your application.

require_once 'vendor/jasny/php-functions/global.php';

Alternatively, add it to the autoload section of composer.json.

"autoload": {
    "files": [
        "vendor/jasny/php-functions/global.php"
    ]
}

Type functions

is_associative_array

boolean is_associative_array(mixed $var)

Check if variable is an associative array.

is_numeric_array

boolean is_numeric_array(mixed $var)

Check if variable is a numeric array.

objectify

stdClass|mixed objectify(array|mixed $var)

Turn an associated array into a stdClass object recursively.

arrayify

array|mixed arrayify(stdClass|mixed $var)

Turn an stdClass object into an associated array recursively.

expect_type

expect_type(mixed $var, string|string[] $type, string $throwable = null, string $message = null)

Validate that an argument has a specific type.

By default a TypeError (PHP 7) is thrown. You can specify a class name for any Throwable class. For PHP 5 you must specify the class name.

The message may contain a %s, which is replaced by the type of $var.

Example
expect_type($input, ['array', 'stdClass']);
expect_type($output, ['array', 'stdClass'], 'UnexpectedValueException', "Output should be an array or stdClass object, got a %s");

Array functions

array_unset

array_unset(array &$array, string $key)

Walk through the array and unset an item with the key. Clones each object, so the originals aren't modified.

array_only

array array_only(array $array, array $keys)

Return an array with only the specified keys.

array_without

array array_without(array $array, array $keys)

Return an array without the specified keys.

array_contains

boolean array_contains(array $array, array $subset, boolean $strict = false)

Check if an array contains a set of values.

This function works as expected with nested arrays or an array with objects.

array_has_subset

boolean array_has_subset(array $array, array $subset, boolean $strict = false)

Check if an array contains a set of values with index check.

This function works as expected with nested arrays or an array with objects.

array_flatten

array function array_flatten(string $glue, array $array)

Flatten a nested associative array, concatenating the keys.

Example
$values = array_flatten('.', [
    'animal' => [
        'mammel' => [
            'ape',
            'bear'
        ],
        'reptile' => 'chameleon'
    ],
    'colors' => [
        'red' => 60,
        'green' => 100,
        'blue' => 0
    ]
]);

Will become

[
    'animal.mammel' => [
        'ape',
        'bear'
    ],
    'animal.reptile' => 'chameleon',
    'colors.red' => 60,
    'colors.green' => 100,
    'colors.blue' => 0
]

extract_keys

array extract_keys(array $array, array $keys)

Get items from array identified by the keys. Will not trigger notices if a key doesn't exist.

$keys may be a mix of a index an assosiated array. With an indexed item, the value is used as key of $array. For an associated item, the key is use as key of $array and the value is used as default. The default value is picked if $array doesn't has the key or the value is null (using isset()).

Example
list($foo, $bar, $useAll) = extract_keys($_GET, ['foo', 'bar', 'all' => false]);

array_join_pretty

string array_join_pretty(string $glue, string $and, array $array);

Join an array, using the 'and' parameter as glue the last two items.

Example
echo "A task to " . array_join_pretty(", ", " and ", $chores) . " has been created.", PHP_EOL;
echo array_join_pretty(", ", " or ", $names) . " may pick up this task.", PHP_EOL;

String functions

str_starts_with

boolean str_starts_with(string $string, $string $substr)

Check if a string starts with a substring.

str_ends_with

boolean str_ends_with(string $string, string $substr)

Check if a string ends with a substring.

str_contains

boolean str_contains(string $string, string $substr)

Check if a string contains a substring.

str_before

string str_before(string $string, string $substr)

Get a string before the first occurence of the substring. If the substring is not found, the whole string is returned.

str_after

string str_after(string $string, string $substr)

Get a string after the first occurence of the substring. If the substring is not found, an empty string is returned.

str_remove_accents

string str_remove_accents(string $string)

Replace characters with accents with normal characters.

str_slug

string str_slug(string $string, string $glue = '-')

Generate a URL friendly slug from the given string.

Cast functions

camelcase

string camelcase(string $string)

Turn a sentence, StudlyCase, snake_case or kabab-case into camelCase.

studlycase

string studlycase(string $string, $ucfirst = true)

Turn a sentence, camelCase, snake_case or kabab-case into StudlyCase.

snakecase

string snakecase(string $string)

Turn a sentence, StudlyCase, camelCase or kabab-case into snake_case.

kababcase

string kababcase(string $string)

Turn a sentence, StudlyCase, camelCase or snake_case into kabab-case.

uncase

string uncase(string $string)

Turn StudlyCase, camelCase, snake_case or kabab-case into a sentence.

Server functions

ip_in_cidr

boolean ip_in_cidr(string $ip, string $cidr)

Check if an IP address is in a CIDR block.

Works with IPv4 and IPv6.

ipv4_in_cidr

boolean ipv4_in_cidr(string $ip, string $cidr)

Check if an IPv4 address is in a CIDR block.

ipv6_in_cidr

boolean ipv6_in_cidr(string $ip, string $cidr)

Check if an IPv6 address is in a CIDR block.

inet_to_bits

string inet_to_bits(string $inet)

Converts inet_pton output to string with bits.

File functions

file_contains

boolean file_contains(string $filename, string $string)

Check if a string is present in the contents of a file.

This function is memory usage friendly by not loading the whole contents of the file at once.

fnmatch_extended

boolean fnmatch_extended(string $pattern, string $path)

Match path against wildcard pattern. This is an extended version of fnmatch.

  • ? Matches a single character, except /
  • # Matches any decimal characters (0-9)
  • * Matches any characters, except /
  • ** Matches any characters
  • [abc] Matches a, b or c
  • {ab,cd,ef} Matches ab, cd or ef

Function handling functions

call_user_func_named_array

mixed call_user_func_named_array(callable $callback, array $param_arr)

Call a callback with named parameters as associative array.

php-functions's People

Contributors

jasny avatar

Watchers

James Cloos avatar Kishore Chandra Sahoo avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.