Help to understand how works PHP's unpack
.
I know that in ruby I can use unpack somehow:
"abcdefgh-abcdefgh-abcdefgh-abcdefgh".unpack("NnnnnN")
=> [1633837924, 25958, 26472, 11617, 25187, 1684366951]
Given the documentation in PHP too. But actually it does not really work.
I need array of 6 elements. Lets try to get it...
$bytes = openssl_random_pseudo_bytes(16);
var_dump(unpack("NnnnnN", $bytes));
array(1) {
["nnnnN"]=>
int(2679895791)
}
var_dump(unpack("N/n/n/n/n/N", $bytes));
array(1) {
[1]=>
int(600384068)
}
var_dump(unpack("N1/n1/n1/n1/n1/N1", $bytes));
array(1) {
[1]=>
int(600384068)
}
var_dump(unpack("N1n1n1n1n1N", $bytes));
array(1) { ["n1n1n1n1N"]=> int(2679895791) }
I found workaround:
var_dump(array_values(unpack("N1a/n1b/n1c/n1d/n1e/N1f", $bytes)));
array(6) {
[0]=>
int(2679895791)
[1]=>
int(39295)
[2]=>
int(42804)
[3]=>
int(32471)
[4]=>
int(39559)
[5]=>
int(600384068)
}
But I think there is a bit of black magic. Prompt please how correctly to use the unpack
function without aliases
(like N1a) and array_values
?
No. Each format is evaluated by itself and overwrites the previous values:
var_dump(unpack("N", $bytes));
array(1) {
[1]=>
int(824184250)
}
var_dump(unpack("N/n", $bytes));
array(1) {
[1]=>
int(32979)
}
var_dump(unpack("N/n2", $bytes));
array(2) {
[1]=>
int(32979)
[2]=>
int(48930)
}
It's actually on the documentation you linked:
Caution Be aware that if you do not name an element, an empty string is used. If you do not name more than one element, this means that some data is overwritten as the keys are the same [...]