Reading Every Two Characters In A String

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
zunebuggy
Forum Commoner
Posts: 41
Joined: Wed Aug 27, 2008 1:22 pm

Reading Every Two Characters In A String

Post by zunebuggy »

I have a string that is like this: 'FF336AD0075CCC'. $msg_len = strlen of this string.

I need to loop through and get every 2 characters in the string and convert it to decimal. Here is what I have but it returns a syntax error.

Code: Select all

 
    for ($msgCnt=1; $msgCnt<=$msg_len; $msgCnt +=2) {
        $hxChar=substr($keyWordString, $keyCnt-1,2);
        $hxVal=hexdec($hxChar);
        $msg_writ=$msg_writ.chr($hxVal);
 
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Reading Every Two Characters In A String

Post by requinix »

For syntax, you might be missing the closing }.

What's $keyCnt?

Also, for fun

Code: Select all

$msg_writ .= implode("", array_map("chr", array_map("hexdec", str_split($keyWordString, 2))))
zunebuggy
Forum Commoner
Posts: 41
Joined: Wed Aug 27, 2008 1:22 pm

Re: Reading Every Two Characters In A String

Post by zunebuggy »

keyCnt should have been msgCnt. That might be part of it. I copied that from another script I wrote that did work and missed changing the variable names in a whole line. It looks like your array line will do everything I need in one line correct?
Thanks.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Reading Every Two Characters In A String

Post by requinix »

zunebuggy wrote:It looks like your array line will do everything I need in one line correct?
If you can understand how it works you're free to use it. If not then you shouldn't: better to have something longer that you know than something shorter that you don't.
Post Reply