1

I have a variable stack in object form:

  • $people->one
  • $people->two
  • $people->three
  • $people->four

I also have an array of data that when applicable, I want to replace those values. The array has things like: Lets call the array $stats

  • "two" => 1
  • "four" => 14

What I have been trying to accomplish (and this was using the double variable, is replace the value in the original object stack with an updated value if in the array.

foreach ($stats as $key => $value) {    
    $data = "people->" . $key;
    $$data = "<strong>" . $$data .  "</strong>";
}

But, that just doesn't look like it should work, and isn't as clean as I would like it. Is there a better way to handle something like this?

Thanks for any help that can be provide.

^^^

Update:

Basically I am trying to wrap around a variable, if the variable shows up in the array. And, then have it print like the original value, except with the wrapped around it.

1
  • I have updated the top to where there are not two $value sets. That was dumb on my part. Commented Feb 3, 2012 at 21:56

3 Answers 3

1
foreach ($arrayvariable as $key => $val) {    
    $value->$key = "<strong>" . $value->$key .  "</strong>";
}

I suspect you meant

$$data = "<strong>" . $value .  "</strong>";

in your question, which would translate to

$value->$key = "<strong>" . $val .  "</strong>";
1
  • When I try something like $people->$key = "<strong>" . $people->$key . "</strong>"; It isn't setting that data point to where I can print it with the orignal $people->two (with the new <strong> wrapper). Commented Feb 3, 2012 at 21:54
0
$value        = new stdClass();
$value->one   = 1;
$value->two   = 2;
$value->three = 3;
$value->four  = 4;

$arr          = array();
$arr['one']   = 11;
$arr['four']  = 14;

foreach($value as $key => &$val){
    if(isset($arr[$key])) {
        $val = $arr[$key];
    }
}

var_dump($value); // object(stdClass)#1 (4) { ["one"]=> int(11) ["two"]=> int(2) ["three"]=> int(3) ["four"]=> &int(14) }
0

If $obj is your object, you can do this.

$key = 'four';
echo $obj->$key;

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.