Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
add comment (requires an account with 50 reputation)

put on hold as off-topic by HamZa, Krishnabhadra, falsetru, Soner Gönül, andr Aug 5 at 7:27

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist" – HamZa, Krishnabhadra, falsetru, Soner Gönül, andr
If this question can be reworded to fit the rules in the help center, please edit the question.

2 Answers

up vote 0 down vote accepted
foreach ($array as &$val) $val['type'] = 'type1';

I think it's fastest way

share|improve this answer
Just did the same thing, SO made me lazy :) – kajacx Aug 4 at 12:49
add comment (requires an account with 50 reputation)
array_walk($array, function(&$value, $key){$value['type'] = 'type1';}) 

would also work in php 5.3+

share|improve this answer
yes, but in this case, it will take a bit more time than foreach with reference – JohnSmith Aug 4 at 12:51
I agree, but you beat me to the foreach answer, So I posted an alternative – user1281385 Aug 4 at 12:53
add comment (requires an account with 50 reputation)

Not the answer you're looking for? Browse other questions tagged or ask your own question.