Skip to content

Instantly share code, notes, and snippets.

@stevenpray
Created December 24, 2017 04:24
Show Gist options
  • Save stevenpray/064648b2d23eacb259ec26122df434d8 to your computer and use it in GitHub Desktop.
Save stevenpray/064648b2d23eacb259ec26122df434d8 to your computer and use it in GitHub Desktop.
<?php
declare(strict_types=1);
/**
* @param mixed $var
* @return bool
*/
function is_int_safe($var): bool
{
return is_numeric($var) && preg_match('/^-?\d*$/', (string)(float)$var);
}
/**
* @param array $keys
* @param array $values
* @return array
*/
function array_combine_merge(array $keys, array $values): array
{
$combined = [];
$keys = array_values($keys);
$values = array_values($values);
$count = max(count($keys), count($values));
for ($i = 0; $i < $count; $i++) {
$value = $values[$i] ?? null;
if (array_key_exists($i, $keys)) {
$combined[$keys[$i]] = $value;
} else {
$combined[] = $value;
}
}
return $combined;
}
/**
* @param string $str
* @param string $separator
* @param bool $capitalize
* @return string
*/
function strtocamel(string $str, string $separator = '_', bool $capitalize = false): string
{
$str = str_replace($separator, '', ucwords($str, $separator));
if (!$capitalize) {
$str = lcfirst($str);
}
return $str;
}
/**
* @param string $str
* @return string
*/
function strtosnake(string $str): string
{
/** @var string[][] $matches */
preg_match_all('!([A-Z][A-Z0-9]*(?=$|[A-Z][a-z0-9])|[A-Za-z][a-z0-9]+)!', $str, $matches);
foreach ($matches[0] as &$match) {
$match = $match === strtoupper($match) ? strtolower($match) : lcfirst($match);
}
return implode('_', $matches[0]);
}
/**
* @param string $glue
* @param array $array
* @return string
*/
function implode_all(string $glue, array $array): string
{
$string = '';
foreach ($array as $item) {
if (is_array($item)) {
$string .= implode_all($glue, $item).$glue;
} else {
$string .= $item.$glue;
}
}
$string = substr($string, 0, 0 - strlen($glue));
return $string;
}
/**
* @param array $array
* @param string $prefix
* @param string $glue
* @return array
*/
function array_flatten(array $array, string $glue = '_', string $prefix = null): array
{
$result = [];
foreach ($array as $key => $value) {
if (is_array($value)) {
/** @noinspection AdditionOperationOnArraysInspection */
$result += array_flatten($value, $glue, $prefix.$key.$glue);
} else {
$result[$prefix.$key] = $value;
}
}
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment