Speeple » Join Speeple | People | Groups | Blogs | News

Speeple Core

PHP Argument Overload via func_num_args() and func_get_args()

MySQL provides functionality for checking if a column or value is in a set, for example:

-- x IN(set) Example:
SELECT * FROM documents WHERE id IN(1, 20, 7, 18)

-- x NOT IN(set) Example:
SELECT * FROM documents WHERE id NOT IN(21, 5, 4, 13)

Using PHP’s function overloading we can easily emulate this method in PHP:

<?php
function in() {
        if (func_num_args() < 2) return false; // Nothing to compare

        $args = array_flip(array_slice(func_get_args(), 1)); // Remove first array item, flip the array so fast key lookup can be used – bypasses slow loops

        return isset($args[func_get_arg(0)]); // Look up using array key – faster than using loops & less code
}
?>

Usage Examples:

<?php
// x IN (set):

if (in(1, 9, 8, 7, 6, 5, 4, 3, 2, 1)) echo 'The number 1 is in our set!';

// x NOT IN (set):

if (!in('cat', 'frog', 'dog', 'snake', 'tiger', 'elephant')) echo 'Cat is not in our set of animals!';

/*
        NOTE:
        This function is not type safe, e.g.:
        in('1', 9, 8, 7, 6, 5, 4, 3, 2, 1) === TRUE

        The string type '1' is equal to the integer 1 in the eyes of the weakly typed PHP interpreter!
*/
?>

The function doesn’t use type safe comparison and because PHP is a weak-typed language statements such as ("1" == 1) evaluate to true. To overcome this, array_key_exists() can be used:

<?php
function in() {
        if (func_num_args() < 2) return false;

        return array_key_exists(func_get_arg(0), array_flip(array_slice(func_get_args(), 1)));
}
?>