PHP: setting object properties inside foreach loop

Is it possible to set property values โ€‹โ€‹of an object using a foreach loop?

I mean something equivalent:

foreach($array as $key=>$value) { $array[$key] = get_new_value(); } 

EDIT: My sample code did nothing, as @YonatanNir and @ gandra404 indicated, so I changed it a bit to reflect what I had in mind

+6
source share
3 answers

You can use a loop containing the names and values โ€‹โ€‹of the properties you want to set.

For example, an object that has the properties "$ var1", "$ var2" and "$ var3", you can set them as follows:

 $propertiesToSet = array("var1" => "test value 1", "var2" => "test value 2", "var3" => "test value 3"); $myObject = new MyClass(); foreach($propertiesToSet as $property => $value) { // same as $myObject->var1 = "test value 1"; $myObject->$property = value; } 
+4
source

Did this example help at all?

 $object = new stdClass; $object->prop1 = 1; $object->prop2 = 2; foreach ($object as $prop=>$value) { $object->$prop = $object->$prop +1; } print_r($object); 

This should output:

 stdClass Object ( [prop1] => 2 [prop2] => 3 ) 

Alternatively, you can do

 $object = new stdClass; $object->prop1 = 1; $object->prop2 = 2; foreach ($object as $prop=>&$value) { $value = $value + 1; } print_r($object); 
+2
source

You can implement the Iterator interface and loop through an array of objects:

 foreach ($objects as $object) { $object->your_property = get_new_value(); } 
0
source

All Articles