I felt that these three array functions were sorely lacking from PHP. They're simple to use and easy to install, and follow the general syntax of the existing array methods that are default to PHP.

Usage

Once they are in a file that is included in the project, they can simply be used in existing code as such:

$myArray = array(5,6,7,8,9);

$val1 = array_insert($myArray,9,1); // $val1 == 1; this is the index that the value 9 has been added at (at index 1)

// Here, $myArray == array(5,9,6,7,8,9);

$val2 = array_insert($myArray,3,-2); // $val2 == 3; this is the index that the value 3 has been added at (2 from the end)

// Here, $myArray == array(5,9,6,7,3,8,9);

$val3 = array_remove($myArray,4); // $val3 == 3; this uses the same method as array_splice and can accept negative values also

// Here, $myArray == array(5,9,6,7,8,9);

$val4 = array_detach($myArray,6); // $val4 == true; it found 6, and removed it, so it is true; if 6 was not in here, it would be false

// Here, $myArray == array(5,9,7,8,9);

$val5 = array_detach($myArray,9,true); // $val5 == true; we removed all values of 9, instead of just 1

// Here, $myArray == array(5,7,8);

Code

function array_insert(&$array, $value, $index = 0) {
    if ($index < 0) $index = count($array) + $index + 1;
    else if ($index > count($array)) $index = count($array);
    $array = array_merge(array_slice($array,0,$index),array($value),array_slice($array,$index));
    return $index;
}
function array_remove(&$array, $index = 0) {
    $values = array_splice($array,$index,1);
    return $values[0];
}
function array_detach(&$array, $obj, $all = false) {
    $found = false;
    for ($i = 0; $i < count($array); $i++) {
        if ($array[$i] == $obj) {
            array_remove($array,$i);
            $found = true;
            if ($all) return $found;
        }
    }
    return $found;
}

Next Post Previous Post