Search code examples
phpformatunpack

Searching the proper format in php unpack function


The output is the result of the codes:

    $bytes= fread($handle,"32");
    print_r(unpack("La/fb/fc/fd/fe/ff/fg/fh",$bytes)); 


Array ( [a] => 20150416 [b] => 1.0499999523163 [c] => 1.25 [d] => 1.0299999713898 
[e] => 1.1900000572205 [f] => 509427008 [g] => 566125248 [h] => 509427008 ) 

How to write the proper format in unpack if the wanted output is as following ?

Array ( [1] => 20150416 [2] => 1.0499999523163 [3] => 1.25 [4] => 1.0299999713898 
[5] => 1.1900000572205 [6] => 509427008 [7] => 566125248 [8] => 509427008 ) 

Solution

  • Use array_values, it keeps the order (first index is 0):

    $bytes = fread($handle,"32");
    $un = unpack("La/fb/fc/fd/fe/ff/fg/fh",$bytes);
    print_r(array_values($un));
    

    Edit (if you want first index 1):

    $bytes = fread($handle,"32");
    $un = unpack("La/fb/fc/fd/fe/ff/fg/fh",$bytes);
    array_unshift($un, NULL);
    $array = array_values($un);
    unset($array[0]);
    print_r($array);