thelolcat
thelolcat

Reputation: 11545

Variable array names

Fatal error: Cannot use string offset as an array

This appears when I try to find a array key by using variable array name:

class FOO {
    protected $arr = array();
    function bar(){
        $aaaaaaaaaaaa = 'arr';
        $this->$aaaaaaaaaaaa[$somekey]; // <-- error
        ...
    }
}

How can I do this with variable array names?

Upvotes: 0

Views: 129

Answers (6)

mindandmedia
mindandmedia

Reputation: 6825

you are first defining $arr as an array, then you are OVER-writing its definition with a string. instead, maybe you wanted to add an element to the list:

$arr = array();

$somekey = 'mykey';
$arr[$somekey] = 'arrVal';

echo $arr[$somekey]

i think, i know what you want now:

a list of arrays...

$arr = array():
$arr['aaaaaaaaaa'] = array();
$arr['aaaaaaaaaa'][$somekey] = 'arrVal';

echo $arr['aaaaaaaaaaa'][$somekey]

and what's up with all the screaming?

Upvotes: 2

Lennart
Lennart

Reputation: 1560

After say

$arr = 'arr';

Variable $arr is no longer a variable, may be what you want to do is add that value to the array in which case try the following:

arr.push('arr');

Then it should work I think

Upvotes: 1

devOp
devOp

Reputation: 3170

$arr is not an array. You first created one but then it's getting a string variable here: $arr = 'arr';.

This is correct:

$arr = array();
$arr[] = 'arr';
$somekey = 0;

$this->$arr[$somekey] 

Upvotes: 2

Michael Krelin - hacker
Michael Krelin - hacker

Reputation: 143099

$this->{$arr}[$somekey]

is what you want (provided that you actually assign array to $this->arr, not just $arr that you reassign later.

Upvotes: 2

Vitamin
Vitamin

Reputation: 1526

@MarcinJuraszek's right, when you assign $arr the second time it's no longer an array.

Anyway, I believe this code does what you intend to

<?php
class foo
{
    public function doStuff()
    {
        $name = 'arr';
        $this->{$name} = array('Hello world!');
        echo $this->{$name}[0];
    }
}

$obj = new foo;
$obj->doStuff();

Upvotes: 2

MarcinJuraszek
MarcinJuraszek

Reputation: 125630

After that part of code:

$arr = 'arr';

$arr is no more an array. It's just a variable containing 'arr' string. So you can't access it as by key.

You should read information from PHP: Arrays - Manual.

Upvotes: 2

Related Questions