LoginSignup
0
0

More than 5 years have passed since last update.

数値を英語の番号(序数)に変換するメソッド

Last updated at Posted at 2017-09-21

使いどころとしてはfor文で回してるときに$iの数値によって英語序数で表記したいときとかですかね
あんまりきれいなコードじゃないですがどうでしょう?

test.php
     /**
     * 数値を英語の番号(10番目まで)に変換します。
     *
     * @param int $int
     * @param bool $is_abbreviation
     * @return string|null
     */
    static function convertIntegerToOrdinalNumberUpToTen(int $int, $is_abbreviation = false) {

        $abbreviation = $is_abbreviation === true ? 'abbreviation' : 'ordinal_number';

        $list = [
            1 => [
                'ordinal_number' => 'first',
                'abbreviation'   => '1st',
            ],
            2 => [
                'ordinal_number' => 'second',
                'abbreviation'   => '2nd',
            ],
            3 => [
                'ordinal_number' => 'third',
                'abbreviation'   => '3rd',
            ],
            4 => [
                'ordinal_number' => 'fourth',
                'abbreviation'   => '4th',
            ],
            5 => [
                'ordinal_number' => 'fifth',
                'abbreviation'   => '5th',
            ],
            6 => [
                'ordinal_number' => 'sixth',
                'abbreviation'   => '6th',
            ],
            7 => [
                'ordinal_number' => 'seventh',
                'abbreviation'   => '7th',
            ],
            8 => [
                'ordinal_number' => 'eighth',
                'abbreviation'   => '8th',
            ],
            9 => [
                'ordinal_number' => 'ninth',
                'abbreviation'   => '9th',
            ],
            10 => [
                'ordinal_number' => 'tenth',
                'abbreviation'   => '10th',
            ]
        ];

        return array_key_exists($int ,$list) === false ? null : $list[$int][$abbreviation];
    }
0
0
8

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