Page 1 of 1

Accessing index of associative array with variable

Posted: Wed Nov 26, 2008 12:09 pm
by bob1234
Hello,

I am a bit new to php. I am trying to access an objects data members with a variable name. Here is a quick example to demonstrate my problem:

Code: Select all

 
<?php
 
error_reporting(E_ALL);
ini_set("display_errors", 1);
 
$testme = new Test();
 
$testme->printTest("test2");
 
class Test
{
        public $example = array("test1"=>1, "test2"=>2, "test3"=>3);
 
        function printTest($testNumber)
        {
                echo $this->$testNumber;
        }
}
 
?>
 

My goal is to have the above print out 2, but instead it prints out

Code: Select all

Notice: Undefined property: Test::$test2
How would I be able to use a variable name to access the index of an associative array?

Re: Accessing index of associative array with variable

Posted: Wed Nov 26, 2008 12:12 pm
by Mark Baker

Code: Select all

 
class Test
{
        public $example = array("test1"=>1, "test2"=>2, "test3"=>3);
 
        function printTest($testNumber)
        {
                echo $this->example[$testNumber];
        }
}
 
?>
 

My goal is to have the above print out 2, but instead it prints out

Code: Select all

Notice: Undefined property: Test::$test2
How would I be able to use a variable name to access the index of an associative array?[/quote]

Re: Accessing index of associative array with variable

Posted: Wed Nov 26, 2008 12:20 pm
by bob1234
I may be missing something, but all you did was quote half of my original post.

Re: Accessing index of associative array with variable

Posted: Wed Nov 26, 2008 12:23 pm
by Eran
The difference is that you wrote:

Code: Select all

echo $this->$testNumber;
And he wrote:

Code: Select all

echo $this->example[$testNumber];
Which should work, since it accesses the array members.