-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?

2 Answers 2

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

I think it's fastest way

2
  • Just did the same thing, SO made me lazy :) Commented Aug 4, 2013 at 12:49
  • 1
    Please don't forget to unset($val) after this code. Commented Jun 6, 2023 at 12:16
2
array_walk($array, function(&$value, $key){$value['type'] = 'type1';}) 

would also work in php 5.3+

2
  • yes, but in this case, it will take a bit more time than foreach with reference Commented Aug 4, 2013 at 12:51
  • I agree, but you beat me to the foreach answer, So I posted an alternative Commented Aug 4, 2013 at 12:53

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.