How can I remove a specific item from an array?

Usually when working with arrays we are in need to remove a targeted element and execute a specific operation with it. In this post we’ll learn how to use the following function to remove an item by value from the designated array.

To remove a specific item from an array you need to traverse the array, check each value with the one you want to remove and then create a new array with all the other elements. The resulting array will not contain the designated item.

If you don’t know how to do that, I encourage you to use the function below. The remove function will even keep the indices as they are without changing each element’s position (or not), meaning that you can have a choice to remove an element and assign its value into a new position or keep the position in place for the record.

function remove($t, $v, $keep_index = false) {
    $ret_arr = array();
    foreach($t as $it)
        if ($keep_index==true){
            $ret_arr[] = ($it!=$v) ? $it : '';
        } else {
            if ($it!=$v){
                $ret_arr[] = $it;
            }
        }
    return $ret_arr;
}

$array = ['hello', 'world'];
print_r(remove($array, 'hello', true));
print_r(remove($array, 'world'));