[K12OSN] PHP and variables

Henry Hartley henryhartley at westat.com
Tue Sep 9 13:06:10 UTC 2008

Doug Simpson wrote:
>> I know how to get data in from a form, but I need to know how to
>> get a string converted from a letter variable to a number variable.
>> Example:
>> Say there are two choices and I am using radio buttons to select
>> which choice the viewer wants.
>> It stores the first choice as "a" and the second choice as "b".
>> This I know how to do.
>> So I would like to convert the a to 1 and the b to 1 and store
>> them each in another variable of their own. I know how to get
>> them into another variable, also.
>> Now, I want to add up the number of "a"s and the number of "b"s .
>> All I really need to know is how to convert a letter to a number
>> in PHP.
>> if choice=a then choice1num=1   <<<<this part
>> if choice=b then choice2num=1   <<<<this part
>> echo choice1num
>> echo choice2num

It isn't completely clear to me what you want to do.

If you have letters a, b, c, and possibly as far as z, then you can use ord() and subtract 60.  Since ord("a") will return 61, you'll end up with a 1 for a, 2 for b, etc.  Is that what you mean?

Or do you want to cound the number of occurrences of a, b, c, etc.?  If so, then convert to a hash.  Inside a loop that goes through all the selections made, have something like this:

        $count[$choice]++ ;

When you're done, $count["a"] will be the number of a's, $count["b"] the number of b's, etc.

The last part of your question (the "All I really need to know") is the least clear part of your email.  Perhaps you can explain what you're trying to do, rather than be quite so specific about how to do it.


More information about the K12OSN mailing list