There is almost identical question, but I have no idea what to do in my case.
I’m just starting with OO PHP and I have this function within my class:
public function show() {
foreach($this->data['fields'] as $field) {
$type = $field['type'];
echo $type;
}
}
Here’s the input data:
my_function('id',
array(
'foo' => 'bar',
'bar' => 'foo',
'fields' => array(
'type' => 'my_type',
'foo' => 'bar',
'etc.' => 'value'),
),
);
Of course echo $field['type'] returns only the first letter of my_type (m).
And I can’t just simply use echo $field as I have multiple keys under this array and it returns my_typebarvalue instead of my_type, the same happens with $field[0] (mbv). What should I do?
There are three key-value pairs in
$this->data['fields']:type => my_type,foo => barandetc. => value. When you use thisforeachsyntax,$fieldwill contain only the value of the pair, which is always a string.The index operator (the brackets after the variable, as in
$foo['bar']) works on strings as well, and returns the character at the given index. Type juggling turns the string'type'into the integer0, and as such you get the first character of the string.I’m not sure what you want, actually, if
echo $fieldis not okay. PHP will not print newlines or separators unless asked, so you might want to tryecho $field . ' 'and see that the values are actually distinct.