Search code examples
phparraysiterationassociative-arraynested-loops

How can I loop associative array respectively


I have following associative array:

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

[1] => Array
    (
        [0] => 125
        [1] => 258
        [2] => 658
        [3] => 128
        [4] => 987
    )

[2] => Array
    (
        [0] => 123
        [1] => 258
    )

[3] => Array
    (
        [0] => 168
    )
 )

I need the following result as string.

   268
   125258658128987
   123258
   168

What I have tried so far;

    <?php
    //consider my array is in $array variable
    for ($i = 0; $i < count($array); $i++)
    {
     foreach ($array[$i] as $res)
     {
     echo $res . '<br/>';
     }
     }
     ?>

But unfortunately I am getting each numbers in a new line. Any suggestion will be appreciated.


Solution

  • You have to echo the <br /> outside the foreach loop:

    for ($i = 0; $i < count($array); $i++)
    {
        foreach ($array[$i] as $res) {
            echo $res;
        }
        echo '<br />';   //<-- Put this outside the foreach loop
    }
    

    Or another option, you can use foreach and implode for a simpler approach

    foreach ($array as $value)
    {
        echo implode('',$value);
        echo '<br />';
    }
    

    Doc: implode()