PHP Binary Strings vs Byte Arrays

In PHP, a binary string and a byte array are different, even though both can represent binary data.


Key Differences Between Binary Strings and Byte Arrays

Feature Binary String ("string") Byte Array ("array" of bytes)
Type "string" (scalar) "array" (compound)
Storage A contiguous sequence of bytes A collection of separate integers
Mutability Immutable (str_replace required) Mutable ($array[0] = 255;)
Access $string[0] returns a string $array[0] returns an integer
Performance More memory-efficient Less efficient due to array overhead
Use Cases File I/O, network protocols, cryptography Byte-by-byte manipulation, calculations

Binary String

A binary string in PHP is a "string" that contains raw binary data. Since PHP strings are binary-safe, they can hold null bytes ("\x00") and other non-printable characters.

Example: Creating a Binary String

$binaryString = "\x00\x01\x02\x03\x04";  // Binary string containing raw bytes
echo bin2hex($binaryString);  // Output: 0001020304

Key Characteristics

  • Stored as a single contiguous block of memory.
  • Supports binary-safe operations.
  • Accessing "$binaryString[0]" returns a one-character string, not an integer.

Example: Accessing Binary String Characters

echo ord($binaryString[0]);  // Output: 0 (ASCII value of first byte)
  • "ord($binaryString[0])" converts the single-character string into an integer.

Byte Array

A byte array in PHP is an array of integers, where each element represents a single byte (0-255).

Example: Creating a Byte Array

$byteArray = [0, 1, 2, 3, 4];
print_r($byteArray);

Key Characteristics

  • Each byte is stored separately as an integer.
  • Directly accessible and modifiable ("$byteArray[0] = 255;").
  • Less memory-efficient compared to binary strings.

Example: Accessing and Modifying Bytes

echo $byteArray[0];  // Output: 0
$byteArray[0] = 255;
print_r($byteArray);  // Output: [255, 1, 2, 3, 4]