1
0

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 1 year has passed since last update.

PHP 配列の要素を区切り文字を指定して連結する implode

Posted at

概要

  • PHPにて配列要素の文字列を連結する方法をまとめる。

やりたいこと

  • 下記のような配列があったとする。

    $array = ['foo', 'bar', 'hoge', 'fuga'];
    
  • 下記の様に配列の要素を/で区切り、一つの文字列にしたい。

    foo/bar/hoge/fuga
    

方法

  • PHPの組み込み関数implodeを使う。

  • 下記のように第一引数に区切り文字を、第二引数に配列を入れると連結した文字列を返す。

    implode(区切り文字, 配列);
    
  • 今回の場合は下記の様になる。

    <?php
    
    $array = ['foo', 'bar', 'hoge', 'fuga'];
    
    $result = implode('/', $array);
    
    echo $result;
    // foo/bar/hoge/fuga
    
  • 区切り文字は何でもいい。

    • カンマとか

      <?php
      
      $array = ['foo', 'bar', 'hoge', 'fuga'];
      
      $result = implode(',', $array);
      
      echo $result;
      // foo,bar,hoge,fuga
      
    • 半角スペースとか

      <?php
      
      $array = ['foo', 'bar', 'hoge', 'fuga'];
      
      $result = implode(' ', $array);
      
      echo $result;
      // foo bar hoge fuga
      
  • ちなみに区切り文字の指定は任意で、特に指定しなければ区切り文字なしで連結だけ行われる。

    <?php
    
    $array = ['foo', 'bar', 'hoge', 'fuga'];
    
    $result = implode($array);
    
    echo $result;
    // foobarhogefuga
    

参考文献

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?