2

I've been getting error from accessing array with string offsets. The array looks something like this:

$array = array(
                    "first" => array("one","two","three"),
                    "second" => array("blabla"),
                    "third" => array("something","else"),
                    "fourth" => array("next","nextnext","nextnextnext")
    );

I'm trying to get one of the inside arrays depending on string I have and I use that string as offset, like this:

$curArray = $array[$this->string];

But everytime I run the script I get an error on that line. Can you please tell me why? The error I get is "Illegal offset type". Thanks

7
  • 1
    What is $this? What is $this->string? Commented Jan 29, 2013 at 19:39
  • To call the third array for example you should use something like this $curArray = $array["third"]; Commented Jan 29, 2013 at 19:41
  • well, the code is a part of function of a class, so $this->string reffers to value of $string property of the object Commented Jan 29, 2013 at 19:42
  • Try var_dump($this->string); and check what it contains Commented Jan 29, 2013 at 19:43
  • it contains in all cases something like this object(SimpleXMLElement)#7 (1) { [0]=> string(3) "second" } Commented Jan 29, 2013 at 19:50

2 Answers 2

1

It is very likely that $this->string isn't what you think it is. This error is caused by a non string or number being used as an array key.

if you do var_dump($this->string); You should be able to see what the value actually is.

Edit: A SimpleXMLElement is an object and therefore can't be used as an array key. You can cast it to a string like so:

$key = (string)$this->string;
$curArray = $array[$key];
Sign up to request clarification or add additional context in comments.

Comments

0

The value of $this->string is not recognized as an actual string value.

You may want to run a print_r ( $this->string ) to get a better idea of what it contains.

See: http://php.net/manual/en/language.types.array.php

You can use the is_string(..) function to figure out of $this->string is valid, and perhaps check with array_key_exists () if your lookup is valid.

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.