0

I think the best way to explain my question is to give an example. Say I have the following object.

$data=new stdClass;
$data->test=new stdClass;
$data->test->test2=6;
$data->s=array('b',6,7);

I want to know how I can read or change any value in the object given the key value as an array.

I know the below won't work:

function doSomething($inputArray1,$inputArray2) {
    $data[  $inputArray1   ]; //6
    $data[  $inputArray2   ]=4; //was array('b',6,7);
}

//someone else provided
doSomething( array('test','test2')  , array('s')  );

Changed to make clear that I do not know the values of the array personally so using $data->test->test2; to get the 6 like I normally would won't work. Also do not know the array length.

1
  • You want to change the objects array value? $data->s[2]? Commented Nov 2, 2016 at 4:52

2 Answers 2

1

Figured it out:

$parts=array('test','test2');


$ref=&$data;
foreach($parts as $part) {
    if (is_array($ref)) {
        $ref=&$ref[$part]; //refrence next level if array
    } else {
        $ref=&$ref->$part; //refrence next level if object
    }
}
echo $ref; //show value refrenced by array
$ref=4; //change value refrenced by array(surprised this works instead of making $ref=4 and breaking the refrence)
unset($ref); //get rid of refrence to prevent accidental setting.  Thanks @mpyw
Sign up to request clarification or add additional context in comments.

2 Comments

Execution unset($ref); is strongly recommended after your task is finished.
thanks @mpyw I am sure that would have caused me all kinds of headaches.
0

As I noted in the comments, you need to access the object/arrays as intended. Their notations are as follows;

  • Object: ->
  • Array: []

So, taking your $data array you've generated, you'd have to access the object/array combination as such:

echo $data->s[2];

Example/Demo

And if you were to access the initial test/test2 itteration (which is set as an object (->)), then you need to access it as an object:

echo $data->test->test2;

1 Comment

that is how I would normally do it if I knew the values in the array. I do not.

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.