CodeIgniter 4 How To Convert Number To Words Tutorial

Share this Article
Reading Time: 9 minutes
386 Views

Inside this article we will see the concept i.e CodeIgniter 4 How To Convert Number To Words Tutorial. Article contains the classified information about Conversion of Numbers to Words using concept of CodeIgniter.

If you are looking for a solution i.e How to Convert number to words using CodeIgniter 4 then this article will help you a lot for this. Tutorial is super easy to understand and implement it in your code as well.

Number To Words means:

120: One Hundred Twenty

4500: Four Thousand and Five Hundreds

Learn More –

Let’s get started.

CodeIgniter 4 Installation

To create a CodeIgniter 4 setup run this given command into your shell or terminal. Please make sure composer should be installed.

$ composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.

Environment (.env) Setup

When we install CodeIgniter 4, we will have env file at root. To use the environment variables means using variables at global scope we need to do env to .env

Either we can do via renaming file as simple as that. Also we can do by terminal command.

Open project in terminal

$ cp env .env

Above command will create a copy of env file to .env file. Now we are ready to use environment variables.

Enable Development Mode

CodeIgniter starts up in production mode by default. You need to make it in development mode to see any error if you are working with application.

Open .env file from root.

# CI_ENVIRONMENT = production

 // Do it to 
 
CI_ENVIRONMENT = development

Now application is in development mode.

Method #1: Number To Words within Controller

Let’s consider a application controller. In this controller we will create a method which handles number to words conversion.

Open project into terminal and create this controller:

$ php spark make:controller DemoController

It will create a controller file DemoController.php inside /app/Controllers folder.

Open DemoController.php file and write this code into it.

<?php

namespace App\Controllers;

use App\Controllers\BaseController;

class DemoController extends BaseController
{
	public function index()
	{
		$word = $this->numberToWord(120);
		print($word);

		echo "<br>";

		$word = $this->numberToWord(4500);
		print($word);

		echo "<br>";

		$word = $this->numberToWord(58010);
		print($word);
	}

	public function numberToWord($num = '')
	{
		$num    = (string) ((int) $num);

		if ((int) ($num) && ctype_digit($num)) {
			$words  = array();

			$num    = str_replace(array(',', ' '), '', trim($num));

			$list1  = array(
				'', 'one', 'two', 'three', 'four', 'five', 'six', 'seven',
				'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen',
				'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'
			);

			$list2  = array(
				'', 'ten', 'twenty', 'thirty', 'forty', 'fifty', 'sixty',
				'seventy', 'eighty', 'ninety', 'hundred'
			);

			$list3  = array(
				'', 'thousand', 'million', 'billion', 'trillion',
				'quadrillion', 'quintillion', 'sextillion', 'septillion',
				'octillion', 'nonillion', 'decillion', 'undecillion',
				'duodecillion', 'tredecillion', 'quattuordecillion',
				'quindecillion', 'sexdecillion', 'septendecillion',
				'octodecillion', 'novemdecillion', 'vigintillion'
			);

			$num_length = strlen($num);
			$levels = (int) (($num_length + 2) / 3);
			$max_length = $levels * 3;
			$num    = substr('00' . $num, -$max_length);
			$num_levels = str_split($num, 3);

			foreach ($num_levels as $num_part) {
				$levels--;
				$hundreds   = (int) ($num_part / 100);
				$hundreds   = ($hundreds ? ' ' . $list1[$hundreds] . ' Hundred' . ($hundreds == 1 ? '' : 's') . ' ' : '');
				$tens       = (int) ($num_part % 100);
				$singles    = '';

				if ($tens < 20) {
					$tens = ($tens ? ' ' . $list1[$tens] . ' ' : '');
				} else {
					$tens = (int) ($tens / 10);
					$tens = ' ' . $list2[$tens] . ' ';
					$singles = (int) ($num_part % 10);
					$singles = ' ' . $list1[$singles] . ' ';
				}
				$words[] = $hundreds . $tens . $singles . (($levels && (int) ($num_part)) ? ' ' . $list3[$levels] . ' ' : '');
			}
			$commas = count($words);
			if ($commas > 1) {
				$commas = $commas - 1;
			}

			$words  = implode(', ', $words);

			$words  = trim(str_replace(' ,', ',', ucwords($words)), ', ');
			if ($commas) {
				$words  = str_replace(',', ' and', $words);
			}

			return $words;
		} else if (!((int) $num)) {
			return 'Zero';
		}
		return '';
	}
}

Add Route

Open Routes.php file from /Config folder and add this route into it.

//...

$routes->get("number-to-words", "DemoController::index");

//...

Once we will call the route, output will be:

One Hundred Twenty
Four Thousand and Five Hundreds
Fifty Eight Thousand and Ten

Method #2: Number To Words (Custom Helper)

Here,

We will create a custom CodeIgniter helper i.e numberToWord() via which we will register the concept of number to words conversion.

We need to register custom helper in CodeIgniter 4 –

  • Create a file number_helper.php inside /app/Helpers folder.

Open number_helper.php from application and write this code into it.

<?php

if (!function_exists("numberToWord")) {

    // Number to words
    function numberToWord($num = '')
    {
        $num    = (string) ((int) $num);

        if ((int) ($num) && ctype_digit($num)) {
            $words  = array();

            $num    = str_replace(array(',', ' '), '', trim($num));

            $list1  = array(
                '', 'one', 'two', 'three', 'four', 'five', 'six', 'seven',
                'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen',
                'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'
            );

            $list2  = array(
                '', 'ten', 'twenty', 'thirty', 'forty', 'fifty', 'sixty',
                'seventy', 'eighty', 'ninety', 'hundred'
            );

            $list3  = array(
                '', 'thousand', 'million', 'billion', 'trillion',
                'quadrillion', 'quintillion', 'sextillion', 'septillion',
                'octillion', 'nonillion', 'decillion', 'undecillion',
                'duodecillion', 'tredecillion', 'quattuordecillion',
                'quindecillion', 'sexdecillion', 'septendecillion',
                'octodecillion', 'novemdecillion', 'vigintillion'
            );

            $num_length = strlen($num);
            $levels = (int) (($num_length + 2) / 3);
            $max_length = $levels * 3;
            $num    = substr('00' . $num, -$max_length);
            $num_levels = str_split($num, 3);

            foreach ($num_levels as $num_part) {
                $levels--;
                $hundreds   = (int) ($num_part / 100);
                $hundreds   = ($hundreds ? ' ' . $list1[$hundreds] . ' Hundred' . ($hundreds == 1 ? '' : 's') . ' ' : '');
                $tens       = (int) ($num_part % 100);
                $singles    = '';

                if ($tens < 20) {
                    $tens = ($tens ? ' ' . $list1[$tens] . ' ' : '');
                } else {
                    $tens = (int) ($tens / 10);
                    $tens = ' ' . $list2[$tens] . ' ';
                    $singles = (int) ($num_part % 10);
                    $singles = ' ' . $list1[$singles] . ' ';
                }
                $words[] = $hundreds . $tens . $singles . (($levels && (int) ($num_part)) ? ' ' . $list3[$levels] . ' ' : '');
            }
            $commas = count($words);
            if ($commas > 1) {
                $commas = $commas - 1;
            }

            $words  = implode(', ', $words);

            $words  = trim(str_replace(' ,', ',', ucwords($words)), ', ');
            if ($commas) {
                $words  = str_replace(',', ' and', $words);
            }

            return $words;
        } else if (!((int) $num)) {
            return 'Zero';
        }
        return '';
    }
}

Usage of Helper

Open DemoController.php and write this code into it.

<?php

namespace App\Controllers;

use App\Controllers\BaseController;

class DemoController extends BaseController
{
	public function __construct()
	{
		helper("number"); // Load helper
	}

	public function index()
	{
		$word = numberToWord(120);
		print($word);

		echo "<br>";

		$word = numberToWord(4500);
		print($word);

		echo "<br>";

		$word = numberToWord(58010);
		print($word);
	}
}

Output

One Hundred Twenty
Four Thousand and Five Hundreds
Fifty Eight Thousand and Ten

We hope this article helped you to learn CodeIgniter 4 How To Convert Number To Words Tutorial in a very detailed way.

Buy Me a Coffee

Online Web Tutor invites you to try Skillshare free for 1 month! Learn CakePHP 4, Laravel APIs Development, CodeIgniter 4, Node Js, etc into a depth level. Master the Coding Skills to Become an Expert in Web Development. So, Search your favourite course and enroll now. Click here to join.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Was this post helpful?

Learn Web Development Courses Risk Free @ $5 only.
Web Development Courses @ $5