-3

Suppose I am looping an array like this:

foreach($cursor as $obj) { ... }

and the values inside are as following:

$obj['name'] => "foo"
$obj['surname'] => "test"

is there a way to add another key and value inside it, directly from the foreach, without using '&'? Something like this:

foreach($cursor as $obj) { $obj['age'] = 24; }

but without using this:

foreach($cursor as &$obj) { $obj['age'] = 24; }

Thanks in advance.

3
  • foreach ($cursor as $key => $obj) {$cursor[$key]['age'] = 24;} Commented Nov 23, 2012 at 15:56
  • Why don't you want to loop "by reference"? IS there a valid reason? Commented Nov 23, 2012 at 16:05
  • yes, here it is: stackoverflow.com/questions/13531554/… Commented Nov 23, 2012 at 16:06

1 Answer 1

7
foreach($cursor as $k => $obj) { 
    $cursor[$k]['age'] = 24; //or whatever else you want to change it to
}
Sign up to request clarification or add additional context in comments.

6 Comments

It adds an empty element into the array with age => 0, and the other elements do not gain age => 24.
@johnsmith Oops, I typed cursor instead of obj. Fixed it.
it still doesn't. The value for 'age' is not added into the array; but this time there no empty array :)
Using $cursor[$k] you get the value of $obj. $obj[$k] makes no sense.
@MihaiStancu You're right, it's late and I don't have my head screwed on straight. Thanks!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.