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

一桁の数字の前に0をつける方法(Laravel)

Posted at

##一桁の数字の前に0をつける方法
1~20の数字があったとする。その中で1~9までの数字には前に0をつけたい。
↓みたいな感じ
01,02,03,04,....

自分で考えた実装はこちら

$numberList = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];

foreach ($numberList as $number) {

     //10以下の数字には0を連結させる
     if ($number < 10) {
         $hoge = '0' . $number;
     } else {
         $hoge= $number;
     }
 };
//01,02,03,04...09

これでも実装はできるが下記の実装の方がスマートなんで紹介しとく。

$numberList = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];

foreach ($numberList as $number) {
    //文字の長さが一桁以上ならtrue
    if (strlen($number) > 1) {
        //$numberを文字列に変換
        $hoge =  strval($number);
    }else{
        //$numberを文字列に変換して0を連結
        $hoge = '0' . strval($number)
    }
 };

//01,02,03,04...09になる

**strlen()**は文字の長さを取得する。
**strval()**は変数を文字列に変換する。

ついでに↓は変数の中身の型を調べることができる。

gettype($hoge);
0
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
0
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?