nagyben
nagyben

Reputation: 938

PHP - print multidimensional array

I'm having a brain-block with this piece of code. I want to print a multidimensional array in PHP where the 'columns' are separated by hyphens and the 'rows' are separated by newlines.

My problem is that my code prints a '-' at the end of each row. This is obvious when looking at my code:

N.B. ($result is a 2D array i.e. $result[][])

foreach($result as $row){
    foreach($row as $column){
            echo $column . "-";
    }
    echo "\n";
}

This is the output:

42-1-1394752507-16.125-
43-1-1394752569-16.125-
44-1-1394752632-16.562-
45-1-1394752693-17.125-

What is the best way to print this out to avoid the trailing - on each row? I could do a check to see if the current $column is the last element in the $row but I don't actually know how to do this

Upvotes: 2

Views: 868

Answers (6)

Johann Bauer
Johann Bauer

Reputation: 2606

Instead of the inner foreach you could just use implode:

implode($row,"-");

Upvotes: 1

thelolcat
thelolcat

Reputation: 11545

I could do a check to see if the current $column is the last element in the $row but I don't actually know how to do this

implode() is the way to go, but if you want to understand how to find out if the current column is the last one:

// foreach (value)
foreach($result as $row){
  $column_count = count($row);

  // for each (key => value)
  foreach($row as $column_index => $column){
    echo $column;

    if($column_index < $column_count - 1){
      echo "-";
  }
  echo "\n";
}

Upvotes: 1

maosmurf
maosmurf

Reputation: 1946

if you also want to avoid a trailing newline, you could use this one-liner:

echo implode(array_map(function($row) {return implode('-', $row);}, $result), "\n");

of course, oneliners are ugly and not clean code.

what does this code do? it uses implode on each row, and array_map creates a flat (1-dimensional) array of already imploded rows. that is again imploded with newline.

finally, this solution is not the most performant one. but it's a neat oneliner :)

Upvotes: 0

keelerm
keelerm

Reputation: 2943

<?php

$row = [
    '42' => [1, 2, 3],
    '43' => [2, 3, 4],
];

array_walk($row, function($item, $key) {
    echo $key . implode('-', $item) . PHP_EOL;
});

Upvotes: 1

user557846
user557846

Reputation:

one option:

foreach($result as $row){
$c='';
    foreach($row as $column){
            $c.= $column . "-";
    }
    $c=rtrim($c,'-');
    echo "$c\n";
}

Upvotes: 0

AbraCadaver
AbraCadaver

Reputation: 78994

implode is your friend:

foreach($result as $row){
    echo implode('-', $row) . "\n";
}

Upvotes: 7

Related Questions