Open In App

PHP | unpack() Function

The unpack() function is an inbuilt function in PHP which is used to unpack from a binary string into the respective format.

Syntax:



array unpack( $format, $data, $offset )

Parameters: This function accepts three parameters as mentioned above and described below:

Return Value: It returns an associative array containing unpacked elements on success, or returns FALSE on failure.

Note: This function is available for PHP 4.0.0 and newer version.

Example 1: This program uses C format to unpack the data from binary string.




<?php
  
var_dump( unpack("C*", "GEEKSFORGEEKS"));
?>

Output:
array(13) {
  [1]=>
  int(71)
  [2]=>
  int(69)
  [3]=>
  int(69)
  [4]=>
  int(75)
  [5]=>
  int(83)
  [6]=>
  int(70)
  [7]=>
  int(79)
  [8]=>
  int(82)
  [9]=>
  int(71)
  [10]=>
  int(69)
  [11]=>
  int(69)
  [12]=>
  int(75)
  [13]=>
  int(83)
}

Example 2:




<?php
  
$binary_data = pack("c2n2", 0x1634, 0x3623, 65, 66);
var_dump(unpack("c2chars/n2int", $binary_data));
?>

Output:
array(4) {
  ["chars1"]=>
  int(52)
  ["chars2"]=>
  int(35)
  ["int1"]=>
  int(65)
  ["int2"]=>
  int(66)
}

Example 3: This example uses i format to unpack the data from binary string.




<?php
  
$binary_data = pack("i3", 56, 49, 54);
var_dump(unpack("i3", $binary_data));
?>

Output:
array(3) {
  [1]=>
  int(56)
  [2]=>
  int(49)
  [3]=>
  int(54)
}

Reference: https://www.php.net/manual/en/function.unpack.php


Article Tags :