String to byte array in php

String to byte array in php

  1. Blog
  2. 15 November 2026
  3. 5 min read

Stefan Bogdanescu

Founder & Senior Architect

Converting Strings to Byte Arrays in PHP for Java Interoperability

When working with legacy systems or microservices where a server is written in Java, you often encounter a specific interoperability hurdle: sending binary data from a PHP application. In Java, the standard approach to serialize a String into bytes is the getBytes() method. While this seems straightforward in an object-oriented language, PHP handles strings as byte streams natively, which can lead to confusion when trying to extract that underlying array of integers for transmission via protocols like TCP sockets using fputs().

The most common stumbling block occurs when developers attempt to manually iterate over a string and convert characters to their integer ASCII values. A typical attempt looks like this:

for($i = 0; $i < strlen($msg); $i++){
    $data .= ord($msg[$i]);
}

This snippet fails immediately because PHP treats $msg as a string, not a character array. Attempting to access $msg[$i] iterates over bytes only if the string is ASCII and you are careful with delimiters, but it does not return a usable scalar value for concatenation in the way intended; more critically, ord() expects a single-character string, and passing an integer or multi-byte sequence results in incorrect behavior. Furthermore, simply concatenating integers into a variable like $data results in one massive integer, not an array of bytes. If you try to pass this large integer to fputs(), the server will interpret it as a 4-byte integer value rather than a stream of data.

To achieve the true equivalent of Java's getBytes() functionality, you must use PHP's built-in conversion functions that handle encoding and byte representation correctly. The most direct solution is pack() combined with strlen(). However, pack('C*', $string) does not exist in standard PHP. Instead, you iterate over the string to build a binary blob, or better yet, rely on functions designed for this exact purpose.

The idiomatic approach in modern PHP is to use str_split() if you need an indexed array of characters, but since we need bytes (integers 0-255), we should look at how the language represents data internally. The most robust method that mirrors Java's behavior without manual loops is using pack with specific format characters or simply treating the string as binary directly.

However, the cleanest and most performant solution often overlooked is that in PHP 7.3+, you can use str_split with a byte length if dealing with UTF-8, but for raw byte conversion matching Java's default behavior (which is usually ISO-8859-1 or UTF-8 depending on the environment), you must specify encoding.

Consider this scenario where you have a string that needs to be sent as raw bytes:

$originalString = "Hello World 123";
// Java's getBytes() typically uses default charset (UTF-8 usually) unless specified.
// We must ensure PHP matches this expectation.
$bytes = str_split($originalString, 1); // This gives chars, not bytes for UTF-8

// The correct way to get an array of byte values:
$byteArray = [];
for ($i = 0; $i < mb_strlen($originalString, 'UTF-8'); $i++) {
    $byteArray[] = ord(mb_substr($originalString, $i, 1, 'UTF-8'));
}

// Or simply using pack if we treat the string as a sequence of bytes directly:
// Note: pack('C*', ...) expects an array of integers.

Wait, there is a simpler, more direct function that exists specifically for this conversion without manual loops: str_split isn't enough because it returns characters, not byte counts for multi-byte characters. The most reliable method to mimic Java's getBytes() (which defaults to UTF-8 in modern contexts) involves converting the string to a binary representation explicitly.

If you strictly need an array of integers representing the bytes:

$source = "Hello";
// Using mb_convert_encoding to ensure we handle the charset correctly
$binaryData = pack('H*', bin2hex($source)); // This is wrong, this packs hex chars

// Correct approach for byte array:
$byteArray = [];
for ($i = 0; $i < strlen($source); $i++) {
    $byteArray[] = ord(substr($source, $i, 1));
}

Actually, the most efficient and "Java-like" way to get a raw byte stream from a string in PHP is simply using the pack function with the 'H*' format on hex data, but that requires pre-conversion. The direct equivalent for sending binary data over a socket is often just treating the string as binary if it's ASCII-compatible.

If the goal is to send this via fputs() to a Java server, you generally do not need an array of integers at all. You can pass the raw binary string directly to fputs(). The confusion arises from the terminology "byte array." In PHP, a string IS a byte stream. To convert it to a format Java's InputStream reads correctly, you simply ensure the encoding matches.

$javaServerSocket = fsockopen($host, $port);
$dataToSend = "Hello World"; // This is already bytes in memory
fputs($javaServerSocket, $dataToSend);

However, if the Java code explicitly expects a byte array object (which it rarely does over sockets; it expects a stream), you might need to construct the integer array. To do this safely with multi-byte characters:

function stringToByteArray(string $str): array {
    $bytes = [];
    for ($i = 0; $i < mb_strlen($str, 'UTF-8'); $i++) {
        $bytes[] = ord(mb_substr($str, $i, 1, 'UTF-8'));
    }
    return $bytes;
}

// Usage
$byteList = stringToByteArray("Ñoño"); // Handles accented chars correctly

The critical trade-off here is performance. Using mb_substr inside a loop adds overhead. For massive data transfers, it is often better to avoid creating the array altogether and send the binary string directly. The only time you need the explicit byte array is if your Java receiver requires parsing the integer array specifically, which is an uncommon pattern for network communication compared to sending raw bytes or base64-encoded strings.

Always verify the character encoding on both ends. If your PHP environment defaults to UTF-8 and the Java server expects ISO-8859-1, you must convert using mb_convert_encoding before extracting bytes. Failure to align these encodings will result in garbled text or transmission errors, regardless of how perfectly you construct the byte array.

Our network