Monday, 27 August 2018

Why can not I echo the value of this multidimensional array in PHP?

This is so incredibly basic that I am totally baffled as to why it doesn't work. I have an array called $elements, and I want to just echo out one of the values.
I use NetBeans as an IDE, and if I use that to examine the contents of the multidimensional array in question, it looks like this:
So far as I can tell, everything looks normal. It is a multidimensional array, where the first level is numbered "0", and the second level has four named entries.
I just want to echo the value of "parameters", which is a string.
However, this code outputs nothing:
echo "This is the value of 'parameters': " .  $elements[0]['parameters'];

Have I got this most basic code wrong in some way?

This is what I get if I do var_dump($elements):
array(1) { [0]=> object(Element)#3 (4) { ["type":"Element":private]=> string(4) "Text" ["resource":"Element":private]=> string(1) "0" ["parameters":"Element":private]=> string(209) "IP1 111.111.111.111 IP2 222.222.222.222 IP3 333.333.333.333 IP4 444.444.444.444 IP5 555.555.555.555 IP6 666.666.666.666 IP7 777.777.777.777 IP8 888.888.888.888 IP9 999.999.999.999 IP10 111.111.111.112" ["parent":"Element":private]=> NULL } }
... and this is the output from print_r($elements):
Array ( [0] => Element Object ( [type:Element:private] => Text [resource:Element:private] => 0 [parameters:Element:private] => IP1 111.111.111.111 IP2 222.222.222.222 IP3 333.333.333.333 IP4 444.444.444.444 IP5 555.555.555.555 IP6 666.666.666.666 IP7 777.777.777.777 IP8 888.888.888.888 IP9 999.999.999.999 IP10 111.111.111.112 [parent:Element:private] => ) )


Your var dump is saying that element 0 is an object, so you will need to access it like so:
echo $elements[0]->parameters;

The problem is that from your dump, the parameters element is marked as private, so you will not be able to access it.
Solutions are:
  • Change parameters to public
  • Write a getter (getParameters()) and use that method to get your parameters.

0 comments:

Post a Comment