lynn
lynn

Reputation: 2968

How do I get the byte values of a string in PHP?

Say I have a string in php, that prints out to a text file like this:

nÖ§9q1Fª£

How do I get the byte codes of this to my text file rather than the funky ascii characters?

Upvotes: 33

Views: 67685

Answers (4)

Roman Hocke
Roman Hocke

Reputation: 4239

If You wish to get the string as an array of integer codes, there's a nice one-liner:

unpack('C*', $string)

Beware, the resulting array is indexed from 1, not from 0!

Upvotes: 24

Adee
Adee

Reputation: 464

If you are talking about the hex value, this should do for you:

$value = unpack('H*', "Stack");
echo $value[1];

Reference

Upvotes: 6

Henrik Paul
Henrik Paul

Reputation: 67723

Ord() does the trick with an ASCII-charset. If you, however, meddle with multibyte strings (like UTF-8), you're out of luck, and need to hack it yourself.

Upvotes: 2

Gautam
Gautam

Reputation: 2065

Use the ord function

http://ca.php.net/ord

eg.

<?php
$var = "nÖ§9q1Fª£ˆæÓ§Œ_»—Ló]j";

for($i = 0; $i < strlen($var); $i++)
{
   echo ord($var[$i])."<br/>";
}
?>

Upvotes: 34

Related Questions