Home >Backend Development >PHP Tutorial >How Can I Convert a PHP String to a Byte Array?
Converting String to Byte Array in PHP
In PHP, there are various ways to convert a string, containing characters and numbers, into a byte array. Similar to Java's getBytes() method, here are a few approaches to achieve this conversion:
Using the ord() Function
Loop through each character in the string using strlen(). For each character, use the ord() function to obtain its ASCII integer value. Store these values in an array or byte array.
for ($i = 0; $i < strlen($msg); $i++) { $data[] = ord($msg[$i]); // Store in an array // or $byte_array .= ord($msg[$i]); // Concatenate in a byte array }
Using the unpack() Function
PHP's unpack() function offers a concise method to convert a string into a structured array of integer values. It allows you to extract and reinterpret the characters in the string as individual bytes.
$byte_array = unpack('C*', 'The quick fox jumped over the lazy brown dog'); var_dump($byte_array);
Note that the values in the $byte_array array are integers representing the ASCII codes for each character, ranging from 0 to 255.
Considering the original code snippet provided, it appears that you were attempting to convert the characters to hex values rather than integer values. To achieve this, you can use the bin2hex() function after obtaining the character's ASCII code:
for ($i = 0; $i < strlen($msg); $i++) { $data .= bin2hex(chr(ord($msg[$i]))); // Convert to hex and concatenate }
Additional Notes
The above is the detailed content of How Can I Convert a PHP String to a Byte Array?. For more information, please follow other related articles on the PHP Chinese website!