0

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?

3

6 Answers 6

2

@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();
Sign up to request clarification or add additional context in comments.

Comments

2

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.

1 Comment

ok i know that :) '...' is where the property declarations end and methods start..
2
$this->{$arr}[$somekey]

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

Comments

2

$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] 

Comments

2

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?

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.