PHP 8.1: SplFixedArray implements JsonSerializable, and json-encodes as an array
SplFixedArray provides the functionality of a fixed array, akin to other programming languages. The difference between a standard PHP array and an SplFixedArray is that that SplFixedArray only allows a fixed number of elements, and the keys will be always integers in the range.
Although a SplFixedArray class instances implement ArrayAccess interface and behave like an array in most programming languages, the json_encode function encoded SplFixedArray instance as objects, as opposed to arrays.
From PHP 8.1 and later, SplFixedArray implements JsonSerializable interface, and encode SplFixedArray instances as arrays.
$array = new SplFixedArray(3);
$array[] = 'Apple';
$array[] = 'Banana';
$array[] = 'Mango';
echo json_encode($array);
The output of the json_encode call will be different in PHP 8.1 and later:
PHP < 8.1
{"0":"Apple","1":"Banana","2":"Mango"}
PHP >= 8.1
["Apple","Banana","Mango"]
SplFixedArray class also implements JsonSerializable interface since PHP 8.1:
- class SplFixedArray implements Iterator, ArrayAccess, Countable {
+ class SplFixedArray implements Iterator, ArrayAccess, Countable, JsonSerializable {
}
Backwards Compatibility Impact
-
Since PHP 8.1, applications that relied to on the
json_encodeoutput ofSplFixedArrayobjects to be an object notation will receive an array notation instead. -
An
SplFixedArrayobject now evaluates totrueforinstanceof JsonSerializable. -
The output of
serializeoperations are unaffected.