-3

Best shown in practice, I have 2-dimensional array like this:

array(3) {
    [0]=> array(2) {
        ["id"]=> string(4) "3229"
        ["name"]=> string(0) "foo"
    }
    [1]=> array(2) {
        ["id"]=> string(4) "2588"
        ["name"]=> string(4) "1800"
    }
    [2]=> array(2) {
        ["id"]=> string(4) "3234"
        ["name"]=> string(4) "8100"
    }
}

And i want to add a ["type"]=> string(0) "type1" to each array so i would get this

array(3) {
    [0]=> array(2) {
        ["id"]=> string(4) "3229"
        ["name"]=> string(0) "foo"
        ["type"]=> string(0) "type1"
    }
    [1]=> array(2) {
        ["id"]=> string(4) "2588"
        ["name"]=> string(4) "1800"
        ["type"]=> string(0) "type1"
    }
    [2]=> array(2) {
        ["id"]=> string(4) "3234"
        ["name"]=> string(4) "8100"
        ["type"]=> string(0) "type1"
    }
}

I know there is a pretty simple way how to do this with foreach and array_push() but is there some simple one-liner for this?

kajacx
  • 12,361
  • 5
  • 43
  • 70

2 Answers2

2
foreach ($array as &$val) $val['type'] = 'type1';

I think it's fastest way

UnknownError1337
  • 1,222
  • 1
  • 12
  • 16
2
array_walk($array, function(&$value, $key){$value['type'] = 'type1';}) 

would also work in php 5.3+

exussum
  • 18,275
  • 8
  • 32
  • 65