8
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

二次元配列でimplodeを使いたい

Last updated at Posted at 2018-07-04

phpにはimplodeという関数がある。

implode
「配列要素を文字列により連結する」
http://php.net/manual/ja/function.implode.php

例えば次のような使い方ができる。

$cards = [1,3,5,6,7,24];
echo implode(' ', $card);

1 3 5 6 7 24
このような出力がされ、for文を回さずにすっきりと書ける。
しかし、二次元配列の時にimplodeを使って出力する場合はどうなるのだろうか。

$cards[0] = [1,3,5,7,12,13];
$cards[1] = [2,3,4,5,1,7,4];
$cards[2] = [3,1,3,5,6,1,3];

上記配列を、

1 3 5 7 12 13
2 3 4 5 1 7 4
3 1 3 5 6 1 3

このように出力したい場合はどうすればいいか。

1つはforeach文を使う方法

foreach($cards as $card){
       echo implode(' ', $card),PHP_EOL;
}

もう1つはarray_mapをつかって書くことができる

array_map
「指定した配列の要素にコールバック関数を適用する」
http://php.net/manual/ja/function.array-map.php

echo implode(PHP_EOL, array_map('imp', $cards));

function imp($cards)
{
     return implode(' ', $cards);
}
8
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?