Page 1 of 1

Iterating an object with an array member

Posted: Thu Jul 14, 2011 11:45 am
by sinecosine
I have a strange problem. I have an object that has an array as a member. When I try to use a foreach loop to iterate through the object members, I have an odd occurrence at the array: is_array() does not seem to recognize that the member is an array. I present the following snippet:

Code: Select all

<?php
class TryObjectIteration
{
    private $_int;
    private $_str;
    private $_arr = array();

    public function __constructor()
    {}

    public function set_privates()
    {
        $this->_int = 55;
        $this->_str = 'I am a string';
        $this->_arr = array ( 'color' => 'red', 'size' => 9, 'valid' => true );
    }

    public function print_object()
    {
        echo '<p>';
        foreach ( $this as $key => $value )
        {
            echo "$key => $value<br />";
            if ( is_array ( $key ) )
            {
                foreach ( $key as $key2 => $value2 )
                {
                    echo "\t$key2 => $value2<br />";
                }
            }
        }
        echo '</p>';
    }
}

$myObj = new TryObjectIteration();
$myObj->set_privates();
$myObj->print_object();
?>
This produces the following outout:

Code: Select all

_int => 55
_str => I am a string
_arr => Array
I was hoping the is_array function would allow me to go into the second foreach, thus printing the elements of the array. Can anyone explain why the is_array() function seems to not recognize $_arr as an array? Thanks in advance!

Re: Iterating an object with an array member

Posted: Thu Jul 14, 2011 12:58 pm
by AbraCadaver
$key is the key or property name, $value is the array:

Code: Select all

    if ( is_array ( $value ) )
    {
        foreach ( $value as $key2 => $value2 )
        {

Re: Iterating an object with an array member

Posted: Thu Jul 14, 2011 1:04 pm
by sinecosine
Doh! Right! Thanks!

Re: Iterating an object with an array member

Posted: Thu Jul 14, 2011 1:06 pm
by AbraCadaver
This might work better and go deeper:

Code: Select all

            if ( is_array ( $value ) )
            {
                $this->print_object($value);
            }