Can an array key be a string with embedded zero bytes?
Can an array key in PHP be a string with embedded zero-bytes?
I wanted to implode a multi-part key with embedded zero-bytes as the delimiter and use it as the key in an associative array, but it doesn't seem to be working. Not sure whether this is a problem with the array access or with array_keys_exists()
.
Does anybody have any idea? Am I going about this the wrong way? Should I be creating a multi-part key in another way?
To clarify, I am trying to eliminated duplicates from user-entered data. The data consists of a product ID, a variation ID, and N fields of textual data. Each of the N fields has a label an开发者_如何学JAVAd a value. To be considered a duplicate, everything must match exactly (product ID, variation ID, all the labels and all the values).
I thought that if a create a string key by concatenating the information with null bytes, I could keep an associative array to check for the presence of duplicates.
From the PHP string documentation:
There are no limitations on the values the string can be composed of; in particular, bytes with value 0 (“NUL bytes”) are allowed anywhere in the string (however, a few functions, said in this manual not to be “binary safe”, may hand off the strings to libraries that ignore data after a NUL byte.)
From the PHP arrays documentation:
A key may be either an integer or a string.
No mention is made of any special case for strings that are array keys.
So, yes.
Like I already said in the comments
print_r(array("\00foo\00bar" => 'works'));
works. However, there is no reason for any of the gymnastics you are doing with implode
or serialize
or null byte keys.
If you want to see whether arrays are identical, then you can just compare them:
$input1 = array('product_id' => 1, 'variation_id' => 2, 'foo' => 'bar');
$input2 = array('product_id' => 1, 'variation_id' => 2, 'foo' => 'bar');
var_dump($input1 === $input2);
will output true
whereas
$input3 = array('product_id' => 1, 'variation_id' => 2, 'foo' => 'foobarbaz');
var_dump($input1 === $input3);
will give false
.
Quoting the PHP Manual on Array Operators:
$a == $b Equality TRUE if $a and $b have the same key/value pairs.
$a === $b Identity TRUE if $a and $b have the same key/value pairs in the same order and of the same types.
Also, PHP has a function for deleting duplicate values from arrays:
array_unique
— Removes duplicate values from an array
And when you set the second argument to SORT_REGULAR
, PHP will compare the arrays for equality, e.g.
$data = array(
array('product_id' => 1, 'variation_id' => 2, 'foo' => 'bar'),
array('product_id' => 1, 'variation_id' => 2, 'foo' => 'bar'),
array('product_id' => 2, 'variation_id' => 2, 'foo' => 'bar')
);
print_r(array_unique($data, SORT_REGULAR));
will reduce the array to only the first and the third element.
精彩评论