Best way to delete "column" from multidimensional array

Solution 1:

Try this:

function delete_row(&$array, $offset) {
    return array_splice($array, $offset, 1);
}

function delete_col(&$array, $offset) {
    return array_walk($array, function (&$v) use ($offset) {
        array_splice($v, $offset, 1);
    });
}

Tested on Ideone: http://ideone.com/G5zRi0

Edit (Amade):

delete_col function can also be slightly modified to work with arrays with missing columns:

function delete_col(&$array, $key) {
    return array_walk($array, function (&$v) use ($key) {
        unset($v[$key]);
    });
}

This can be used e.g. when you need to iterate over an array and remove some columns in each step. A function using array_splice instead of unset would not be appropriate in such scenarios (it's offset-based and not key-based).

Solution 2:

The PHP manual for array_walk() states (emphasis added):

Only the values of the array may potentially be changed; its structure cannot be altered, i.e., the programmer cannot add, unset or reorder elements. If the callback does not respect this requirement, the behavior of this function is undefined, and unpredictable.

That sounds to me as if mpyw's and Amade's answer might work but cannot be relied on.

A safer solution might be the following:

function delete_col(&$array, $key)
{
    // Check that the column ($key) to be deleted exists in all rows before attempting delete
    foreach ($array as &$row)   { if (!array_key_exists($key, $row)) { return false; } }
    foreach ($array as &$row)   { unset($row[$key]); }

    unset($row);

    return true;
}