Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Unpack function returns array with starting index 1 in PHP

Tags:

php

Why unpack() function in PHP returns an array of binary data starting with the array index 1.

$str = "PHP";
$binary_data = unpack("C*",$str);
print_r($binary_data);

The above PHP scripts prints as below:

Array ( [1] => 80 [2] => 72 [3] => 80 )

like image 405
user2644574 Avatar asked Dec 23 '13 15:12

user2644574


People also ask

Does PHP array start at 1?

By default in PHP the array key starts from 0.

What is unpack PHP?

The unpack() function unpacks data from a binary string.

What is indexed array in PHP?

PHP indexed array is an array which is represented by an index number by default. All elements of array are represented by an index number which starts from 0. PHP indexed array can store numbers, strings or any object. PHP indexed array is also known as numeric array.

How do you declare an associative array in PHP?

Associative Array - It refers to an array with strings as an index. Rather than storing element values in a strict linear index order, this stores them in combination with key values. Multiple indices are used to access values in a multidimensional array, which contains one or more arrays.


1 Answers

The array is an associative array with named keys, not a regular array with numeric keys. The idea is that you will name each format code and the result array will use those names as the array keys.

For example:

<?php
$str = "PHP";
$binary_data = unpack("C*letter",$str);
print_r($binary_data);

Result:

Array
(
    [letter1] => 80
    [letter2] => 72
    [letter3] => 80
)

From the PHP manual:

The unpacked data is stored in an associative array. To accomplish this you have to name the different format codes and separate them by a slash /. If a repeater argument is present, then each of the array keys will have a sequence number behind the given name.

Example #1 unpack() example

<?php
$binarydata = "\x04\x00\xa0\x00";
$array = unpack("cchars/nint", $binarydata);
?>

The resulting array will contain the entries "chars" with value 4 and "int" with 160.

Example #2 unpack() example with a repeater

<?php
$binarydata = "\x04\x00\xa0\x00";
$array = unpack("c2chars/nint", $binarydata);
?>

The resulting array will contain the entries "chars1", "chars2" and "int".

like image 171
John Kugelman Avatar answered Sep 21 '22 23:09

John Kugelman