LoginSignup
1
0

More than 5 years have passed since last update.

【PHP】配列の要素を半角スペース区切りで出力する

Last updated at Posted at 2016-05-01

条件

  • 配列の要素を半角スペース区切りで出力する
  • 末尾の要素は半角スペースでなく改行で出力する

1次元配列の場合

$array = ["red", "blue", "white"];
$space_separated = implode(" ", $array);
echo $space_separated . "\n";

多次元配列の場合

$array = ["red", ["blue", "gold", ["green", "pink"]], ["white", "brown"]];
$number_of_value = count($array, COUNT_RECURSIVE);

$count = 0;
echoWithHalfSpace($array, $number_of_value);

function echoWithHalfSpace($array, $number_of_value) {
    global $count;
    foreach ($array as $value) {
        $count++;
        if (is_array($value)) {
            echoWithHalfSpace($value, $number_of_value);
        } elseif ($number_of_value === $count) {
            echo $value . "\n";
        } else {
            echo $value . " ";
        }
    }
}

もっとスマートな方法があるかも。

関連

【Ruby】配列の要素を半角スペース区切りで出力する

1
0
2

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
1
0