Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

[1]+[2] != [1,2] (behavior of array union operator on non-associative arrays)

[1=>0]+[2=>0] yields [1=>0,2=>0]. But is there any trick to use such syntax sugar for [1]+[2]. So [1]+[2] yeilds [1,2]?

note: My concern is about such syntax, not about other related PHP functions.

like image 765
Handsome Nerd Avatar asked Jan 28 '26 04:01

Handsome Nerd


2 Answers

Use array_merge() instead. I stumped across so much of strange behavior of + used with arrays that I promised myself to never use it ever again.

like image 95
Slava Avatar answered Jan 29 '26 18:01

Slava


+ is the array union operator, which will skip existing keys.

You want array_merge() which will concatenate them in your example (it does that for arrays with numeric keys).

Unfortunately for you, there is no way to overload the + operator to perform anything different.

like image 29
alex Avatar answered Jan 29 '26 20:01

alex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!