Best way to delete "column" from multidimensional array

Horen picture Horen · May 15, 2013 · Viewed 31k times · Source

I have a multidimensional php array that represents a table like this

-------------
| A | 0 | A |
|---|---|---|
| 0 | 0 | 0 |
|---|---|---|
| A | 0 | A |
-------------

so the array looks like this:

array (size=3)
  0 => 
    array (size=3)
      0 => string 'A' (length=1)
      1 => string '0' (length=1)
      2 => string 'A' (length=1)
  1 => 
    array (size=3)
      0 => string '0' (length=1)
      1 => string '0' (length=1)
      2 => string '0' (length=1)
  2 => 
    array (size=3)
      0 => string 'A' (length=1)
      1 => string '0' (length=1)
      2 => string 'A' (length=1)

Now i want to delete the second row and the second column (this is just a simplified example btw).
Deleting the row is easy:

array_splice($array, 1, 1);

I found this approach but was wondering if there was a simpler way (similar to the row) of deleting the column as well? Maybe transposing the array first?

Answer

mpyw picture mpyw · May 15, 2013

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).