replace_properties

Merge objects, preserve null

Definition

object replace_properties(object $object, object $properties, boolean $insertOnMissing)

Merges $object and $properties. Similar to merge, but with following differences:

  • can only merge two objects,
  • replaces array properties instead of concatenating them,
  • is able to replace values with null,
  • replaces the values of type object immediately rather than calling performing replace_properties on them again.

Parameters

object $object

First object to merge.

object $properties

Second object to merge.

boolean $insertOnMissing

If true, adds properties from $properties that are not present in $object. If not, only replaces the ones that are already present in $object, and doesn't add any new ones.

Returns

object

Object obtained by merging $properties into $object. All the properties, even the properties with null, object and array values will be overwritten in $object, in contrast to merge.

Examples

{
  "John1": {
    "middleName": "Jim",
    "lastName": "Smith",
    "age": 42,
    "address": {
      "street": "Main Street",
      "houseNumber": 1,
      "cohabitants": ["Jane", "Julia"]
    },
    "siblings": ["Jade", "Jack"]
  },
  "John2": {
    "middleName": null,
    "lastName": "Doe",
    "address": {
      "street": "High Street",
      "apartmentNumber": 2,
      "cohabitants": ["Jane", "James"]
    },
    "siblings": ["Jerry"]
  }
}
{
  john: replace_properties(John1, John2, `true`)
}
{
  "john": {
    "middleName": null,
    "lastName": "Doe",
    "age": 42,
    "address": {
      "street": "High Street",
      "apartmentNumber": 2,
      "cohabitants": ["Jane", "James"]
    },
    "siblings": ["Jerry"]
  }
}