85 lines
3.1 KiB
PHP
85 lines
3.1 KiB
PHP
<?php
|
|
namespace {
|
|
if(!function_exists('array_all')) {
|
|
/**
|
|
* Checks if all array elements satisfy a callback function.
|
|
*
|
|
* @param mixed[] $array The array that should be searched.
|
|
* @param callable(mixed $value, mixed $key): bool $callback The callback function to call to check each element.
|
|
* @throws InvalidArgumentException If any of the argument types were not as expected.
|
|
* @return bool The function returns true, if callback returns true for all elements. Otherwise returns false.
|
|
*/
|
|
function array_all(array $array, $callback): bool {
|
|
if(!is_callable($callback))
|
|
throw new InvalidArgumentException('$callback must be a callable');
|
|
|
|
foreach($array as $key => $value)
|
|
if(!$callback($value, $key))
|
|
return false;
|
|
|
|
return true;
|
|
}
|
|
}
|
|
|
|
if(!function_exists('array_any')) {
|
|
/**
|
|
* Checks if at least one array element satisfies a callback function.
|
|
*
|
|
* @param mixed[] $array The array that should be searched.
|
|
* @param callable(mixed $value, mixed $key): bool $callback The callback function to call to check each element.
|
|
* @throws InvalidArgumentException If any of the argument types were not as expected.
|
|
* @return bool The function returns true, if callback returns true for all elements. Otherwise returns false.
|
|
*/
|
|
function array_any(array $array, $callback): bool {
|
|
if(!is_callable($callback))
|
|
throw new InvalidArgumentException('$callback must be a callable');
|
|
|
|
foreach($array as $key => $value)
|
|
if($callback($value, $key))
|
|
return true;
|
|
|
|
return false;
|
|
}
|
|
}
|
|
|
|
if(!function_exists('array_key_first')) {
|
|
/**
|
|
* Gets the first key of an array.
|
|
*
|
|
* @param mixed[] $array An array.
|
|
* @return int|string|null Returns the first key of array if array is not empty; null otherwise.
|
|
*/
|
|
function array_key_first(array $array) {
|
|
foreach($array as $key => $_)
|
|
return $key;
|
|
|
|
return null;
|
|
}
|
|
}
|
|
|
|
if(!function_exists('str_contains')) {
|
|
/**
|
|
* Determine if a string contains a given substring.
|
|
*
|
|
* @param string $haystack The string to search in.
|
|
* @param string $needle The substring to search for in the haystack.
|
|
* @return bool
|
|
*/
|
|
function str_contains(string $haystack, string $needle): bool {
|
|
return strpos($haystack, $needle) !== false;
|
|
}
|
|
}
|
|
|
|
if(!function_exists('str_starts_with')) {
|
|
/**
|
|
* Checks if a string starts with a given substring.
|
|
*
|
|
* @param string $haystack The string to search in.
|
|
* @param string $needle The substring to search for in the haystack.
|
|
* @return bool
|
|
*/
|
|
function str_starts_with(string $haystack, string $needle): bool {
|
|
return strpos($haystack, $needle) === 0;
|
|
}
|
|
}
|
|
}
|