views:

74

answers:

4

Hello, I have a multidimensional array object, and in a loop I would like to append an iterator to the key and obtain the value. Sample code for demonstration:

    $array_object->example1 = 1;
    $array_object->example2 = 2;


$i = 1;

while ($i <= 2) {

       echo ($array_object->example . $i); //this does not work
       //how to accomplish same?
       $i++
    }

Thank you in advance for any suggestions.

+6  A: 

I think variable variables will solve your problem, immediately:

$example = "example" . $i;
echo $array_object->$example;

But you may want to consider making $array_object->example an array, and accessing it like:

echo $array_object->example[$i];
yjerem
Thanks this works.
netefficacy
+2  A: 
$n = "example" . $i;

echo $array_object->$n;
goffrie
hanks this works.
netefficacy
+1  A: 

Yes, but you need to set up the variable first, before using the -> operator...

while ($i <= 2) {
        $property = 'example' . $i;  // or "example$i", whichever you prefer
        echo ($array_object->$property);
        $i++
    }

EDIT: damn I'm slow replying...

Ben
Thanks this works.
netefficacy
+8  A: 

echo $array_object->{'example' . $i};

nathan
This is the right way to do it, IMO. Same for array keys.
Alex JL
Thanks this works.
netefficacy