3 ms·
It's funny. I don't have much experience with php, and I had to actually run your last example to know that it appended the values (instead of recreating the ar
by Wilya 15y ago
It's funny. I don't have much experience with php, and I had to actually run your last example to know that it appended the values (instead of recreating the array with a single value each time).
Is there an append operator, or something more explicit ? '+=' seems to do something strange..
- ars 15y ago[] IS the append operator. And += only works right if both sides are arrays. If not the right side will be converted. += is really intended for hashmaps, not integer indexes, for those use [].
- sapphirecat 15y ago+= does union-by-key: any keys present in the right array, and not in the left, are appended to the left. `array_merge` will append all numeric keys from the right array to the left, under new key values, as if you used [] one-by-one; for string keys, all keys from the right are copied into the left, possibly overwriting what was there. In real code, I either have all-numeric or all-string keys, and `array_merge` does what I want in bulk operations: it's essentially equal to Python list.extend and dict.update, respectively. `+` on arrays is basically useless for me.
- MindTwister 15y agoIf you want something more explicit you probably want array_push($array,$val1,$val2,$val....);
- pacmon 15y agoNot sure exactly what you were trying. Using the [] syntax is common for appending elements (using the next available key). Otherwise you can use the array functions (array_push/pop/etc). As for plain operators, here is how PHP handles array operators: http://www.php.net/manual/en/language.operators.array.php http://www.php.net/manual/en/language.operators.array.php