Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic access to a PHP array

Tags:

arrays

php

I tried to access with $this->$arrDataName[$key] on the element with the key $key from the array $this->$arrDataName. But PHP interpretes that wrong.

I tried it with { } around the $arrDataName to $this->{$arrDataName}[$key], but it doesn't work.

On php.net I found an advice, but I can't realize it.

In order to use variable variables with arrays, you have to resolve an ambiguity problem. That is, if you write $$a[1] then the parser needs to know if you meant to use $a[1] as a variable, or if you wanted $$a as the variable and then the [1] index from that variable. The syntax for resolving this ambiguity is: ${$a[1]} for the first case and ${$a}[1] for the second.

Perhaps anyone can help me.

Thanks!

EDIT:

I think it doesn't work, but I forgot to fill the array.
Finally it works. :)
This is the solution: $this->{$arrDataName}[$key]

like image 643
CSchulz Avatar asked Jul 13 '10 09:07

CSchulz


2 Answers

Your syntax is correct:

$this->{$varName}[$key]

You can also use an extra variable for this:

$myTempArr = $this->$arrDataName;

$myTempArr[ $key ];

IMHO, readability is better that way...

like image 62
Macmade Avatar answered Oct 14 '22 20:10

Macmade


<?php
    class Foo {
        public function __construct() {
            $this->myArray = array('FooBar');
            $arrayName = 'myArray';
            echo $this->{$arrayName}[0];
        }
    }
    new Foo;

This worked perfectly for me, it printed FooBar.

like image 32
NikiC Avatar answered Oct 14 '22 20:10

NikiC