Search code examples
phparraysstringmultidimensional-arrayimplode

How do I print a multidimensional array that varies with depth in php?


I have the following example of array output. I need to find a way to convert this array to a string or output the emails in an organized way. I have tried implode but I only receive an "Array" output. Please help!

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [0] => Email
                )

            [1] => Array
                (
                    [0] => [email protected]
                )

            [2] => Array
                (
                    [0] => [email protected]
                )

            [3] => Array
                (
                    [0] => [email protected]
                )

            [4] => Array
                (
                    [0] => [email protected]
                )

            [5] => Array
                (
                    [0] => [email protected]
                )

        )

)

Solution

  • for ($i = 0; $i < count($arr[0]); $i++) {
        for ($j = 0; $j < count($arr[0][$i]); $j++) {
            echo $arr[0][$i][$j];
        }
    }
    

    The above will output each string of the array.
    The only question I have is why you are storing single strings so deep in an array? Perhaps we could see more of the code?

    The below code would be simpler for what you provided:

    $arr[] = "Email";
    $arr[] = "[email protected]";
    $arr[] = "[email protected]";
    $arr[] = "[email protected]";
    $arr[] = "[email protected]";
    $arr[] = "[email protected]";
    
    for ($i = 0; $i < count($arr); $i++) {
        echo $arr[$i];
    }
    

    Even better, use array keys instead:

    $arr["Email"][] = "[email protected]";
    $arr["Email"][] = "[email protected]";
    $arr["Email"][] = "[email protected]";
    $arr["Email"][] = "[email protected]";
    $arr["Email"][] = "[email protected]";
    
    for ($i = 0; $i < count($arr["Email"]); $i++) {
        echo $arr["Email"][$i];
    }