LoginSignup
1
0

More than 5 years have passed since last update.

foreachで最初と最後を判別して処理する

Posted at

備忘録
reset()
end()
を使用する方法もあるが下記だと、値の重複にも対応できる

qiita.php
function body_import ($bodyColumn){
    $body = '';
    $length = count($bodyColumn);
    foreach($bodyColumn as $i => $value) {
        if ($i === 0) {
            //最初
            $body .= '{'.$i.':"'.$value.'",';
        }
        elseif($i === $length - 1){
            //最後
            $body .= $i.':"'.$value.'"},';
        }
        else {
            $body .= $i.':"'.$value.'",';
        }
    }
    return $body;
}
1
0
1

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