CodeIgniter How To Convert Number To Words Tutorial

Reading Time: 9 minutes
1,361 Views

Converting numerical figures into their corresponding words is a useful functionality often required in various financial or data processing applications. In CodeIgniter 4, implementing this feature allows developers to transform numeric values into their verbal representation, enhancing readability and usability for end-users.

In this tutorial, we’ll see the process of converting numbers to words within a CodeIgniter 4 application.

Number To Words means:

120: One Hundred Twenty

4500: Four Thousand and Five Hundreds

Read More: Step by Step How To Setup Cron Jobs in CodeIgniter 4 Tutorial

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 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 '';
	}
}

Read More: How To Cache Database Query Using CodeIgniter Cache?

Add Route

Open Routes.php file from /app/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)

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 –

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

Open file 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 '';
    }
}

Read More: How To Integrate ChatGPT API in CodeIgniter 4 Tutorial

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

That’s it.

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

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

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.