MagicHat
MagicHat

Reputation: 429

Best way to implode multidimensional array

I see some questions but no work to me.

In a for loop i receive an array like that:

array(1) { [0]=> array(1) { [0]=> string(1) "4" } } 

array(1) { [0]=> array(2) { [0]=> string(1) "3" [1]=> string(1) "4" } }

array(1) { [0]=> array(7) { [0]=> string(1) "1" [1]=> string(1) "2" [2]=> string(2) "30" [3]=> string(2) "43" [4]=> string(2) "65" [5]=> string(2) "53" [6]=> string(3) "634" } }

I need implode that values with "-", my desired output isa string:

4

3-4

2-30-43-65-53-634

I try some ways, but no work, some ideia for do it simple?

Upvotes: 0

Views: 3853

Answers (1)

Phillip Weber
Phillip Weber

Reputation: 564

If it is a two dimensional array and would like to output all elements, you could use a foreach loop and output the implode of each like so:

$mainArray = [
    [4],
    [3, 4],
    [2, 30, 43, 65, 53, 634]];

foreach($mainArray as $key => $secArray){
    echo implode('-', $secArray) . '<br/>';
}

PHP Implode

Notice the return type of implode is a string.

Upvotes: 2

Related Questions