5 useful tiny Php helper functions
Babak
Posted on May 13, 2022
Here I am going to introduce five useful Php functions that I usually use in my projects.
- Does an array of keys exists in an array? You can check multiple keys existence inside an array.
function array_keys_exists(array $keys, array $arr)
{
return !array_diff_key(array_flip($keys), $arr);
}
$sample = [1, 2, 3, 4, 5];
array_keys_exists([2, 5], $sample) // Returns True
- Delete an item from an array using its value.
function delete_array_item_by_value($array, $value)
{
if (($key = array_search($value, $array)) !== false) {
unset($array[$key]);
}
return $array;
}
$sample = [1, 2, 3, 4, 5];
delete_array_item_by_value($sample, 4) // $sample = [1, 2, 3, 5];
- Want to apply a closure on items of an array? You can use
array_func_map
function array_map_recursive($callback, $array)
{
$func = function ($item) use (&$func, &$callback) {
return is_array($item) ? array_map($func, $item) : call_user_func($callback, $item);
};
return array_map($func, $array);
}
- Generate random int with a fixed length
function get_random_int(int $length): int
{
$res = '';
for ($i = 0; $i < $length; $i++) {
$res .= mt_rand(0, 9);
}
if ($res[0] == 0) {
$res = mt_rand(0, 9) . substr($res, 1);
}
return (int)$res;
}
get_random_int(4) // Returns 6234
- Checks for all parameters are empty or not.
function all_empty()
{
foreach (func_get_args() as $arg)
if (empty($arg))
continue;
else
return false;
return true;
}
all_empty([], [], [3, 4]) // Returns False
all_empty([], [], []) // Returns True
💖 💪 🙅 🚩
Babak
Posted on May 13, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.