Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Set object properties inside a foreach loop

Tags:

php

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

I mean something equivalent to:

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

EDIT: My example code did nothing, as @YonatanNir and @gandra404 pointed out, so I changed it a little bit so it reflects what I meant

like image 772
ElectricSid Avatar asked Jul 30 '15 12:07

ElectricSid


2 Answers

You can loop on an array containing properties names and values to set.

For instance, an object which has properties "$var1", "$var2", and "$var3", you can set them this way :

$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;
}
like image 124
Random Avatar answered Nov 12 '22 01:11

Random


Would 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
)

Also, you can do

$object = new stdClass;
$object->prop1 = 1;
$object->prop2 = 2;
foreach ($object as $prop=>&$value) {
    $value = $value + 1;
}
print_r($object);
like image 25
Steve Lockwood Avatar answered Nov 11 '22 23:11

Steve Lockwood