• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home ยป Resolved: I get a different behavior after unset() elements

Resolved: I get a different behavior after unset() elements

0
By Isaac Tonny on 18/06/2022 Issue
Share
Facebook Twitter LinkedIn

Question:

I get a strange behavior when I remove data from my array with unset
And I append more objects to the array
When I convert $array into an object I get this key values insted of index values
Expected output

Answer:

That’s because php unset doesn’t reduce the length of the array, it just empty the given key.
Since it doesn’t change the length, whe. You do $array[] = something you continue incrementing the index, creating the 2 and 3 index you are seeing.
When you do json_encode, since the keys doesn’t start from zero (or aren’t contiguous), it need to represent this array as an object.
Exemplifying:
Can only be serialized to
Because you can’t define the index of an array item using JSON.

Solution


You can still use unset(), but you need to get only array values using the array_values() function:

If you have better answer, please add a comment about this, thank you!

arrays php
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: Why reference in pointer array doesn’t have data?

24/03/2023

Resolved: EntityFramework creates/runs migrations using parameterless DataContext instance

24/03/2023

Resolved: Visual Studio 2022 crashes when using breakpoints

24/03/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.