In other words, what value can be assigned to $key so that the following two lines create exactly the same result:
$arr[] = $value;
$arr[$key] = $value;
The task I need to solve looks like the following: I need to add a new value to an array using either the key if specified, or next available numeric key if key is not specified:
protected $_arr;
...
public function addValue($value, $key = NULL) {
$this->_arr[$key] = $value;
}
Working solutions is like this:
public function addValue($value, $key = NULL) {
if($key === NULL) $this->_arr[] = $value;
else $this->_arr[$key] = $value;
}
I suspect there is no such value for the key as I tried obvious NULL and '' (empty string), and neither brings desired result.
There's currently no way to set array
$keyas something that would automatically increment the number key index.Even the
$arr[] = 'value';syntax doesn't do what you exactly wrote - it doesn't find "next available numeric key", it instead increments the highest found number. Example:Results in:
To fill all the gaps, you'd need to use an algorithm that finds them - e.g. one that stores the last used numeric index, then increments it and checks if the index is free until it finds next free one.
And if you don't need to fill the gaps, your shown solution is what I'd just use.