DEV Community

Babak
Babak

Posted on • Updated on

5 useful tiny Php helper functions

Here I am going to introduce five useful Php functions that I usually use in my projects.

  1. 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);
}
Enter fullscreen mode Exit fullscreen mode
$sample = [1, 2, 3, 4, 5];
array_keys_exists([2, 5], $sample) // Returns True
Enter fullscreen mode Exit fullscreen mode
  1. 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;
}
Enter fullscreen mode Exit fullscreen mode
$sample = [1, 2, 3, 4, 5];
delete_array_item_by_value($sample, 4) // $sample = [1, 2, 3, 5];
Enter fullscreen mode Exit fullscreen mode
  1. 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);
}
Enter fullscreen mode Exit fullscreen mode
  1. 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;
}
Enter fullscreen mode Exit fullscreen mode
get_random_int(4) // Returns 6234
Enter fullscreen mode Exit fullscreen mode
  1. 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;
}
Enter fullscreen mode Exit fullscreen mode
all_empty([], [], [3, 4]) // Returns False
all_empty([], [], []) // Returns True
Enter fullscreen mode Exit fullscreen mode

Top comments (0)