Accessing index of associative array with variable

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
bob1234
Forum Newbie
Posts: 5
Joined: Fri Oct 31, 2008 3:48 pm

Accessing index of associative array with variable

Post 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?
Mark Baker
Forum Regular
Posts: 710
Joined: Thu Oct 30, 2008 6:24 pm

Re: Accessing index of associative array with variable

Post 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]
bob1234
Forum Newbie
Posts: 5
Joined: Fri Oct 31, 2008 3:48 pm

Re: Accessing index of associative array with variable

Post by bob1234 »

I may be missing something, but all you did was quote half of my original post.
User avatar
Eran
DevNet Master
Posts: 3549
Joined: Fri Jan 18, 2008 12:36 am
Location: Israel, ME

Re: Accessing index of associative array with variable

Post 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.
Post Reply