1

I have array like this:

$array = [
    'Category 1',
    'Category 2',
    [
        [
            'SubCategory 1',
            'SubCategory 2'
        ],
        [
            'SubCategory 3',
            'SubCategory 4',
            [
                [
                    'SubSubCategory 1',
                    'SubSubCategory 2'
                ]
            ]
        ],
        [
            'SubCategory 4',
            'SubCategory 5',
            [
                [
                    'SubSubCategory 3',
                    'SubSubCategory 4'
                ]
            ]
        ]
    ]
];

And i try do recursion:

function recursive($array)
{
    foreach($array as $key => $val) {
        if(is_array($val)) {
            recursive($val);
        }
        echo $val;
    }
}

It throws an notice "Notice: Array to string conversion" because

   [2] => array(
        [0] => array(..)
        [1] => array(..)
        ..
    );

And also echo Array

In this case, when the array has such a layout. How can I avoid that notice?

3
  • it would help if you could tell us the purpose of your recursive function and your desired output. Commented Jul 16, 2018 at 9:49
  • 1
    'category 2' => array(...this is not true in your code above. "Category 2" in your array is a simple string at index 1 of the array. Then index 2 is an array, separately. Are you trying to create an associative array? Commented Jul 16, 2018 at 9:53
  • I corrected, thanks Commented Jul 16, 2018 at 10:00

1 Answer 1

6

You only want to echo the value if it is not an array, so just add an else.

function recursive($array)
{
    foreach($array as $key => $val) {
        if(is_array($val)) {
            recursive($val);
        } else {
            echo $val;
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.