5 ms·
I disagree. The behavior you exhibit makes more sense than the behavior you imagine. You start with an _empty_ array, then (somehow) set the third element of t
by kingdomcome50 7y ago
I disagree. The behavior you exhibit makes more sense than the behavior you imagine.
You start with an _empty_ array, then (somehow) set the third element of that array? That makes very little sense.
Had you _initialized_ your example as an array with a length of 3, your desired behavior would, indeed, manifest.
- cliffy 7y agoThe problem is PHP calling an ordered map an array. Array in pretty much every other language means a sequence indexed by integers. Ideally the maintainers of PHP would rename it and deprecate the use of `array()` over a long period of time.
- zeroimpl 7y agoThe PHP documentation refers to them as "associative arrays", which is technically correct, but I agree I'm not sure how they could have conflated these concepts so badly.
- tyingq 7y agoI believe the "associative array" terminology came from Perl. Though Perl's associative arrays don't have any guaranteed order. And Perl also has normal arrays.
- mattkrause 7y agoIn that situation, Matlab allocates an array of length 3, fills it with “empty” values (depending on the type), and then sets the third element to the value. That’s what I’d have expected to happen here too...
- zeroimpl 7y agoWould you expect it to do that if somebody wrote the following? $id = 12835151; $arr[$id] = Get_thing_with_id( $id );
- jhasse 7y agoyes.
- jrwr 7y agoIn my bog standard PHP I would do $thing = Get_thing_with_id( $id ); if(!empty($thing)){process($thing);}
- mattkrause 7y agoIf $arr were an array I would, though I'd cringe at the wasted space (unless it were a sparse array). Obviously, I'd agree that a map/associative array/dict/etc is a better choice here; I'm just annoyed about the name.
- coldtea 7y ago>You start with an _empty_ array, then (somehow) set the third element of that array? That makes very little sense. Well, there's no reason a language could not initialize an empty array to some initial capacity, either on declaration or when you add an indexed element.
- kingdomcome50 7y agoI guess my reasoning is that: $arr = [] doesn't appear to be initializing to any capacity. So that after: $arr[2] = "two" I would expect: count($arr) === 1 And honestly, sure. A language could be designed to pad the array with empty values if you specify an index greater than the upper bound (or lesser than the lower bound). I believe a sibling mentioned matlab did something like that. But is that really better behavior or just different behavior? I don't really see an important difference. My point was that the criticism was fairly weak. PHP, indeed, has a very useful abstraction in its concept of "array". Most of the hate should be directed at the name, not the construct.