Category: snippets

  • PHP Delete element from array with array_splice()

    array_splice()

    If you use array_splice() the keys will be automatically reindexed, but the associative keys won’t change opposed to array_values() which will convert all keys to numerical keys.

    Also array_splice() needs the offset, not the key!, as second parameter.

    Code

    <?php
    
        $array = array(0 => "a", 1 => "b", 2 => "c");
        array_splice($array, 1, 1);
                           //↑ Offset which you want to delete
    
    ?>

    Output

    Array (
        [0] => a
        [1] => c
    )

    array_splice() same as unset() take the array by reference, this means you don’t want to assign the return values of those functions back to the array.

  • Splunk max min avg group by date

    Data:
    _time Value
    11/24/13 10:00:00 8
    11/25/13 10:01:00 6
    11/26/13 10:02:00 4

    Query:
    … | rename _time as Date | convert timeformat=”%F” ctime(Date) | stats max(Value) as Max, min(Value) as Min, avg(Value) as Avg by Date

  • PHP check mobile browser

    function isMobileDevice(){
    $aMobileUA = array(
    ‘/iphone/i’ => ‘iPhone’,
    ‘/ipod/i’ => ‘iPod’,
    ‘/ipad/i’ => ‘iPad’,
    ‘/android/i’ => ‘Android’,
    ‘/blackberry/i’ => ‘BlackBerry’,
    ‘/webos/i’ => ‘Mobile’
    );

    //Return true if Mobile User Agent is detected
    foreach($aMobileUA as $sMobileKey => $sMobileOS){
    if(preg_match($sMobileKey, $_SERVER[‘HTTP_USER_AGENT’])){
    return true;
    }
    }
    //Otherwise return false..
    return false;
    }

  • Bash script to compare two files

    #!/bin/sh
    echo ‘Check Gemfile…’;
    if diff path/file1 path/file2 >/dev/null ; then
    echo ‘Same’;
    else
    echo ‘Different’;
    fi

  • Modify private variable using PHP ReflectionProperty

    class Foo
    {
    private $bar = ‘0’;

    public function bar()
    {
    return $this->bar;
    }
    }

    $foo = new Foo;
    $attribute = new ReflectionProperty($foo, ‘bar’);
    $attribute->setAccessible(true);
    $attribute->setValue($foo, ‘1’);
    var_dump($foo->bar());