Jump to content

Echoing ASCII code


phpdev@dr

Recommended Posts

I have a php page that splits a string into chars and then echoes the ASCII code for each char. I'm trying to get it print the original value => ASCII code, splitted by :,  like:

 

A => 65: B=>66: C => 67:

 

It is currently echoing: =>65 : =>66: =>67:

Any one, please?

 

Thanks,

 

 

Link to comment
https://forums.phpfreaks.com/topic/182651-echoing-ascii-code/
Share on other sites

Well, if the input is a string, then this will work

 

<?php

function strToASCII($textStr, $sepStr=' => ', $delimStr=' : ')
{
    $strLen = strlen($textStr);
    $resultAry = array();

    for($i=0; $i<$strLen; $i++)
    {
        $resultAry[] = "{$textStr[$i]}{$sepStr}" . ord($textStr[$i]);
    }

    return implode($delimStr, $resultAry);
}

$text = "Test";
echo strToASCII($text);

//Output:
//
// T=>84 : e=>101 : s=>115 : t=>116

?>

Link to comment
https://forums.phpfreaks.com/topic/182651-echoing-ascii-code/#findComment-964023
Share on other sites

This is what I have:

 

<?php

$string = $_post ['string']

for($i = 0; $i != strlen($string); $i++)
{

     $asciiString .= "&#".ord($string[$i]).";";

}

$asciiCode = str_replace("&", "&", $asciiString);

echo "String in ASCII:<br>";

echo $asciiString;

echo "<br>The code:<br>";

echo $asciiCode;

?>

Link to comment
https://forums.phpfreaks.com/topic/182651-echoing-ascii-code/#findComment-964028
Share on other sites

Just a tip: It probably doesn't make much different in this particular case (as I assume these are relatively small strings), but it is slower to have the PHP parser continually compute a value in a for loop when you can define the value before hand.

 

In this line

for($i = 0; $i != strlen($string); $i++)

 

The parser must compute the length of $string on each iterration of the loop. If the string can change length on each iterration, that would be fine. but, if the string will be 'fixed' for the duration of the loop, then it is considered better form to define a variable with that length

 

$stringLength = strlen($string);
for($i = 0; $i < $stringLength ; $i++)

 

Link to comment
https://forums.phpfreaks.com/topic/182651-echoing-ascii-code/#findComment-964068
Share on other sites

Or set the length of the string inside the first parameter for the for loop to make things look cleaner:

 

for($i = 0, $stringLength = strlen($string); $i < $stringLength ; $i++)

 

 

I like that better. I always forget about putting additional parameters within for loops like that.

Link to comment
https://forums.phpfreaks.com/topic/182651-echoing-ascii-code/#findComment-964075
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.