Browse ALL the snippets ! - Page 2 of 6

Stumbled upon this somewhere sometime, just leaving it here for posterity.

//*
this_is_ran();
/*/
this_is_not_ran();
//*/

// Now just remove the first slash :

/*
this_is_not_ran();
/*/
this_is_ran();
//*/

Working with dates and times in JS is quite uneasy. If you're as hurried as I am, just copy-paste this to be able to get current time :

var getCurrentTime = function() {
    var d = new Date(),
        t = [d.getHours(), d.getMinutes(), d.getSeconds()],
        i;

    for (i in t) {
        t[i] = '' + parseInt(t[i]);

        while (t[i].length < 2) {
            t[i] = '0' + t[i];
        }
    }

    return t.join(':');
};

This little beauty lets you use call_user_func_array with an associative array, specifying arguments by name : no more bad signature pain !

function call_user_func_assoc($function, $args = array())
{
    // Does the function exist ?
    try {
        if (strpos($function, '::')) {
            list($class, $method) = explode('::', $function);
            $r = new ReflectionMethod($class, $method);
        } else {
            $r = new ReflectionFunction($function);
        }
    } catch (\ReflectionException $e) {
        throw new \Exception($e->getMessage());
    }

    // Get parameter list
    $params = $r->getParameters();
    $keys = array();
    $missing = array();

    foreach ($params as $param) {
        $keys[] = $param->name;

        if (! array_key_exists($param->name, $args)) {
            try {
                $param->getDefaultValue();
            } catch (\ReflectionException $e) {
                $missing[] = $param->name;
            }
        }
    }

    // If we spotted missing mandatory parameters, we exit
    if ($missingno = count($missing)) {
        throw new \Exception('Missing mandatory parameter'.($missingno > 1 ? 's' : '').': '.implode(', ', $missing));
    }

    // Prepare values
    $values = array();

    foreach ($keys as $key) {
        if (array_key_exists($key, $args)) {
            $values[] = $args[$key];
        }
    }

    return call_user_func_array($function, $values);
}

// Use it !

call_user_func_assoc('myFunction', array('param2' => 'test', 'param3' => 'foo', 'param1' => 'bar'));
call_user_func_assoc('myClass::myMethod', array('param2' => 'foo', 'param1' => 'bar'));

This can come in handy on a production deployment, or when working with people with bad habits... It turns every call to alert to a call to console.log :

window.alert = function(msg) { console.log(msg); };

This function helps you get over PHP's inconsistencies regarding the data located in the $_FILES superglobal.

/* This gives you the following format (whether the requested key contains multiple files or not) :

    array(
        0: array(
            'name' => ...,
            'type' => ...,
            'tmp_name' => ...,
            'error' => ...,
            'size' => ...
        ),
        1: ...
    )
*/

function getStandardizedFiles($key)
{
    $files = array();

    if (array_key_exists($key, $_FILES)) {
        foreach ($_FILES[$key] as $property => $data) {
            if (! is_array($data)) {
                $data = array($data);
            }

            foreach ($data as $index => $value) {
                if (! array_key_exists($index, $files)) {
                    $files[$index] = array();
                }

                $files[$index][$property] = $value;
            }
        }
    }

    return $files;
}

Here are two useful tips to cast booleans very easily.

$boolean = !!$anything; // cast anything to a boolean
$integer = +$boolean; // cast a boolean to 0 or 1

Need symbols, and can't be bothered to embed images or icon fonts ? Why not draw these directly with CSS ? The power of LESS brings you arrows and the burger (menu) icon more easily than ever !

.arrow-up(@size, @color) {
    border-top: none;
    border-right: @size solid transparent;
    border-bottom: @size solid @color;
    border-left: @size solid transparent;
}

.arrow-right(@size, @color) {
    border-top: @size solid transparent;
    border-right: none;
    border-bottom: @size solid transparent;
    border-left: @size solid @color;
}

.arrow-down(@size, @color) {
    border-top: @size solid @color;
    border-right: @size solid transparent;
    border-bottom: none;
    border-left: @size solid transparent;
}

.arrow-left(@size, @color) {
    border-top: @size solid transparent;
    border-right: @size solid @color;
    border-bottom: @size solid transparent;
    border-left: none;
}



.burger(@width, @thickness, @gutter, @color) {
    display: inline-block;
    vertical-align: middle;
    position: relative;
    width: @width;
    height: @thickness * 3 + @gutter * 2;
    border-width: @thickness 0;
    border-style: solid;
    border-color: @color;

    &:after {
        content: '';
        position: absolute;
        top: @gutter;
        left: 0;
        width: @width;
        height: @thickness;
        background-color: @color;
    }
}

Here's a quick method to make sure a string has exactly 0 or 1 slash at its end.

function trailSlash($s, $force = true)
{
     return rtrim($s, '/').($force ? '/' : '');
}

// Usage :
// $url = trailSlash($url); makes sure $url ends with /
// $url = trailSlash($url, false); makes sure it doesn't

Dislike var_export and print_r ? Would like to have var_dump spit its output to a variable ? There you go !

function dump($var)
{
    ob_start();
    var_dump($var);

    return ob_get_clean();
}

Think you can beat it under PHP 5.4 ?

$extension = strtolower(array_pop(explode('.', $filename)));