Hi, here's a description of the problem I'm trying to solve:

write words_to_int.php, which computes and outputs the integer that corresponds to the words that the user has entered. For example, if the user enters "two four one", your program computes the integer 241 and outputs it; if the user enters "three one one two", your program computes the integer 3112 and outputs it.

Important

You must calculate this, not just echo a 2 followed by a 4 followed by a 1.
You must calculate an integer, not create a string: your program must not use any concatenation.
So, in effect, for two four one you want to add (2 × 102) to (4 × 101) and to (1 × 100), to get 241. For three one one two, you want to add (3 × 10 to the power of 3) to (1 × 10 to the power of 2) to (1 × 10 to the power of 1) to (2 × 10 to the power of 0), to get 3112.

Here's what I've written so far:

    $words = trim( $_GET['words'] );
    if ( $words != '' )
    {
        $words = explode( ' ', $words );
        foreach ($words as $word)
        {
            if ($word == 'zero')
            {
                $words[] = 0;
            }
            elseif ($word == 'one')
            {
                $words[] = 1;
            }
            elseif ($word == 'two')
            {
                $words[] = 2;
            }
            elseif ($word == 'three')
            {
                $words[] = 3;
            }
            elseif ($word == 'four')
            {
                $words[] = 4;
            }
            elseif ($word == 'five')
            {
                $words[] = 5;
            }
            elseif ($word == 'six')
            {
                $words[] = 6;
            }
            elseif ($word == 'seven')
            {
                $words[] = 7;
            }
            elseif ($word == 'eight')
            {
                $words[] = 8;
            }
            elseif ($word == 'nine')
            {
                $words[] = 9;
            }

        $size = count($word);
        $position = $size-1;    
        echo $position;

        }


        foreach ($words as $word)
        {
        $number = $word * (pow(10, $position));
        echo "<p>$number</p>";
        }   

This doesn't give me the correct position of the word entered for some reason and I don't think my calculations are correct.
Any help is appreciated. Thanks!

$position in your last loop is incorrect. You should set it to the size of the word array before the loop, and decrement it inside that loop. Also, you are adding the numbers to the original word array. Use a second one.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.