Search code examples
phpcountwordshuman-readable

Php - return count() in words


I have the following in my code:

 $my_count = count($total_elements[$array_object]);

$my_count now contains the number of elements in $total_elements[$array_object]. I want to convert this number into its corresponding natural number (zero, one, two, ...)

In this specific case , I only have 5 numbers:

$numbers  = array(
    2  => 'two',
    3  => 'three',
    4  => 'four',
    5  => 'five',
    6  => 'six',
);

How to retrieve the number of elements in a given array and then echo the corresponding natural number (human readable number) from the array? Or better yet - is there a better way of doing this?

(I have found some functions or classes to do just that - but now those are way too bloated for the simple case I need now)

Now, of course I can do this with switch():

switch ($my_count) {
    case 0:
        echo "zero";
        break;
    case 1:
        echo "one";
        break;
    case 2:
        echo "two";
        break;
      // etc...
}

But it just looks so not elegant to me. And also quite stupid if one have more than 10 numbers.

I am sure that there is a more elegant way of achieving that, and even though now I have only 5 numbers, I would like to have some function to re-use in other cases .

(I am sorry if this is a stupid question - but - searching here on SE or Google with keywords PHP - words and count() I only found answers related to counting words in string)


Solution

  • If it's only a handful of number:

    $number = count($yournameit);
    $count_words = array( "zero", "one" , "two", "three", "four" );
    echo $count_words[$number];