0

I seem to be unable to access an array inside an array with index.

this

var_dump($graphed[0]);

give me this

array (size=2)
  'date' => string '02-03-15' (length=8)
  'weight' => string '82.327015155' (length=12)

this

var_dump($graphed[0]['weight']);

gives me this

 string '82.327015155' (length=12)

BUT this

var_dump($graphed[0][1]);

gives me THIS

A PHP Error was encountered

Severity: Notice

Message: Undefined offset: 1

Filename: progress/compare.php

Line Number: 17

null

I have no idea where to go from here. Everything I know about PHP tells me this shouldn't be happening.

By the way, this

echo phpversion();

gives me

 5.5.12

Am I crazy? What's going on?

4

1 Answer 1

2

PHP makes a clear destinction between associative elements (with a key) and indexed elements (with an index). You can't access an element with a key in such way. In other words: they are not interleaved. PHP sees an array as a composition of an Array(List) (like you known them in Java) and a HashMap. The difference with Java is that the keys are furthermore guaranteed to be ordered. But that doesn't mean the keys themselve correspond to an index. In a HashMap<T> you neither can get the i-th value.

Example:

php > var_dump(array(1,2,3,'foo'=>'bar',7));
array(5) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
  ["foo"]=>
  string(3) "bar"
  [3]=>
  int(7)
}

In other words, "foo" doesn't map on an index, the index numbering only considers indexed elements. For the indexer, it's as if "foo" => "bar" doesn't exist.

You can however obtain the list of keys - which is an indexed array - and then pick that key as is written here:

$keys = array_keys($graphed[0]);
echo $graphed[0][$keys[1]];

PHP guarantees key ordering so it's safe to do so (given you know of course the order in advance, or know what you are doing).

Note that the keys include the indices:

php > var_dump(array_keys(array(1,2,3,'foo'=>'bar',7)));
array(5) {
  [0]=>
  int(0)
  [1]=>
  int(1)
  [2]=>
  int(2)
  [3]=>
  string(3) "foo"
  [4]=>
  int(3)
}
Sign up to request clarification or add additional context in comments.

3 Comments

Excellent explanation and excellent answer. I always appreciate getting both. Will checkmark if I have success with it.
A note of advice, the comments on java didn't apply to me, perhaps my assumption made it seem so.
@Goose: well it is only meant in case you don't know how HashMaps work and want to look them up, you can find the mechanism in the java documentation. But it is probably not the essential part of the answer ;).

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.