arrayOrEmpty.php
Table of Contents
Functions
- arrayOrEmpty() : array<int|string, mixed>
- Returns the given value when it is an array, and an empty array when it is not.
Functions
arrayOrEmpty()
Returns the given value when it is an array, and an empty array when it is not.
arrayOrEmpty(mixed $value) : array<int|string, mixed>
Reach for this when a value of unknown shape — a decoded payload, an option
read from a configuration, a field of a response — has to be read as a record
or a list : what is not an array becomes nothing to read, so the reads that
follow answer null instead of tripping over a scalar.
⚠️ This is not toArray(), which wraps what it is given instead of
dropping it : toArray( null ) answers [ null ] — a list holding one item —
where this function answers []. The two read almost the same at a call site
and behave in opposite ways, so pick on the question being asked :
- « read this as an array, or give me nothing » →
arrayOrEmpty() - « make a list out of this lone value » →
toArray()
An array is returned untouched, keys, order and emptiness included.
Parameters
- $value : mixed
-
The value to read as an array.
Tags
Return values
array<int|string, mixed> —The value itself when it is an array, an empty array otherwise.