Array of Objects in PHP | Create, Sort, Filter, Merge, Search, Etc

How to work with an array of objects in PHP code

PHP array of objects

Can you have arrays of objects in PHP

Yes, you can definitely create, store, filter, merge and work with an array of objects in PHP. You can decode JSON objects as arrays as well as create array collections of PHP arrays. PHP offers many solutions to work with an array of objects.

This article will break down 2 common scenarios when working with arrays of objects in PHP. Visitors come to us many times to ask questions about working with PHP classes and objects as well as JSON objects. Both situations are common but do have unique requirements.

Let’s first get into PHP classes and objects. Then we will follow it up with

Working with PHP Classes and Objects

PHP was originally designed as a purely procedural language. Starting in PHP 4 and greatly extending into PHP 5, it has adopted many OOP concepts. Today, PHP is a highly flexible language that offers all of the benefits and functionalities of your standard object-oriented languages.

This also includes Classes and Objects

PHP has base-level generic objects called stdObjects. These objects only contain properties and are generally used for model requirements. In reality, you will likely be creating your own custom PHP classes which are extensions of PHP objects. Classes are equivalent to an object in PHP. Anytime you instantiate a new class in PHP, you will be creating an object.

Working with JSON Objects in PHP

Parsing JSON content is one of the first tasks for many PHP developers. You get JSON arrays and content when connecting with various 3rd party APIs as well as responses from your own REST-based APIs. It is important that PHP developers know how to successfully work with JSON if they want to succeed and grow as a developer.

PHP has had native support for JSON since version 5. The 2 primary functions are json_encode and json_decode. You will use json_encode whenever you need to encode your PHP arrays into a JSON string. Use json_decode when you want to parse your JSON into a PHP multidimensional array or array of PHP stdObjects. We will get into those details further into the article.

Let’s get started.

How to create an array of objects in PHP 

Define your results array with a variable.

Create a for or foreach loop that creates new PHP objects.

Instantiate a new object or class within the loop

Assign the desired properties within your loop.

Use the array_push function or shorthand to insert a new element into PHP array.

Print your results with the print_r function to validate expectations.

Continue processing functional requirements.

<?php 
// Intro into creating arrays of objects in PHP
// 

$dogsResults = [];
$contentArray = [
  [
    "name" => "charles",
    "breed" => "mixed",
    "father" => "frank",
    "mother" => "susie"
  ],
  [
    "name" => "susie",
    "breed" => "Border Collie",
    "father" => "grant",
    "mother" => "samantha"
   ],
   [
     "name" => "john",
     "breed" => "Chihuaha",
     "father" => "unknown",
     "mother" => "samantha"
    ]
];

class Dog
{
  public $name;
  public $breed;
  public $father;
  public $mother;
}

foreach ($contentArray as $key =>$content) {
  $dog = new Dog();
  $dog->name = $content['name'];
  $dog->breed = $content['breed'];
  $dog->father = $content['father'];
  $dog->mother = $content['mother'];
  $dog->id = $key;
}

print_r($dogsResults);

In the above example, we have successfully created an array of PHP objects. We have a dog class that we instantiate and then push the results into our dogsResults array. This is a very simple example to show the beginning and simplest ways of making arrays of objects inside PHP.

We will use the above content to build upon the rest of our article and use it as a reference.

Creating arrays of JSON objects in PHP with json_encode

Creating arrays of JSON objects in PHP is a common scenario. You may have a multidimensional PHP array that you have received from an API or an array of PHP objects that you have modeled from your database. You will use the json_encode function to convert the PHP array of objects into a JSON-encoded array of objects.

  1. Assign or establish your initial PHP array of objects or multidimensional array
  2. Use the php json_encode function to encode your array into json
  3. json_encode has an optional 2nd parameter where you can pass in predefined constants for more configuration.
  4. json_encode’s 3rd optional parameter is depth. The default is 512
  5. Print your results to validate expectations
  6. Continue processing your functional requirements.
// We will use the same dogsResult content that we had created in our first example of creating arrays of PHP objects.
// assumed: array of PHP objects ($dogsResults)

$dogListJson = json_encode($dogsResults);

print_r($dogListJson);

Notes on using json_encode with your array of objects

  • Private Variables: json_encode will encode any public properties in your PHP objects by default. It will not be able to access or encode your private variables. You will need to create a custom PHP function or a PHP serializer class in these cases. I recommend having a serializer class that you convert your model class into with public properties.
  • Depth: The json_encode function defaults to a depth of 512. This is likely fine in most use cases, but there’s a good chance you won’t know the final depth of your array of objects or multidimensional array. Ideally, it would be nice if there was a way to do -1 and have it traverse the whole tree. This isn’t the case.
  • Expecting JSON objects and getting arrays: This is one that will likely get you at some point. You’ve encoded your PHP array, looped through it on the front end, and then your JS errors out because you get an empty array when expecting an object. Why is that? Because json_encodes defaults empty items to arrays. Use the JSON_FORCE_OBJECT constant in the second parameter of the json_encode function.

Additional Articles on using json_encode in php when working with PHP objects

How to Decode JSON array of objects in PHP with json_decode

decoding a JSON array of objects into a PHP array of objects is straightforward. You can use the json_decode function itself if you want to convert the array into PHP stdObjects. Most of the time you will want to decode the JSON content into a PHP class model. You can use the array_map class to help in this case.

  1. Receive the JSON content and assign it to a unique variable.
  2. Include your PHP class that will need to be serialized.
  3. Run the json_decode function with the JSON content as the first parameter and assign to a new variable.
  4. Add the boolean true as the second parameter to create a multidimensional array.
  5. Use the PHP array_map function and assign the results to a new results variable.
  6. The first parameter of the array_map function is a callable function that passes the array value.
  7. Pass in the json_decoded results as the second parameter in the array_map function.
  8. Instantiate and return a new desired PHP class inside of the callback function of array_map
  9. Print and verify the results
  10. Continue processing the functional requirements as expected.
// Functional requirements:
// Receive JSON dog data from our front-end application.
// decode the JSON content
// Serialize the dog content into our Dog Model class

// Our Dog model class is our class that we will use to save into our database.
class DogModel
{
  private $name;
  private $breed;
  private $father;
  private $mother;

  public function __construct(array $content)
  {
     if (!isset($content['name']) || !isset($content['breed']) || !isset($content['father']) || !isset($content['mother'])) {
        throw new Exception("Failed required properties");
     }
     foreach ($content as $key => $value) {
       if ($this->$key) {
         $this->$key = $value;
        }
     }
  }
}

// dogJson is a sample json string that we are getting back from our frontend.
$dogJson = '
[
  {
    "name": "charles",
    "breed": "mixed",
    "father": "frank",
    "mother": "susie"
  },
  {
    "name": "susie",
    "breed": "Border Collie",
    "father": "grant",
    "mother": "samantha"
  },
  {
    "name": "john",
    "breed": "Chihuaha",
    "father": "unknown",
    "mother": "samantha"
  }
]
';

// Lets run json_decode to turn our json array of objects into PHP array.
$dogsDecoded = json_decode($dogJson, true);

// Lets serialize our PHP array into an array of dog model classes.
$dogResults = array_map(
  function($val) {
    return new DogModel($val);
  },
  $dogsDecoded
);
print_r($dogResults);

How to check the value of an array of objects in PHP

I recommend creating a custom function that uses the native PHP array_map function whenever you want to check the values of PHP arrays of objects. This way you can call itself recursively if needed. Checking an object’s value within an array when following this method.

  1. Create your custom function called checkResults
  2. Include 3 paramters in your function: 1 – array, 2 the property, and 3 the evaluation value.
  3. Run the PHP array_map function on the array and pass the other 2 params in a use statement
  4. Run an if statement inside of the array_map callback function to verify the value has the expected property
  5. Throw an Exception whenever the expectedProperty isn’t found.
  6. When property is found, you can verify whether the property equals the expected value
  7. Return an array that shows the verification
  8. Check the final array with print_r or var_dump
  9. Confirm the results meet your expectations
  10. Continue processing.
// Functional requirements:
// We need to check a value inside our array of objects in PHP.
// Make a list of the values on the results with if it equaled expected value.

// Note: We are using the example array of Dog objects from our first example in PHP.
// Assume that we have already decoded and serialized our data into PHP.
// You can review above example if you need to decode or serialize.

// $dogsResult assumes to exist.


function checkResults(array $dogs, string $expectedProperty, string $expectedValue): array 
{
  $results = array_map(
    function($val) use ($expectedValue, $expectedProperty) {
      if (!isset($val->$expectedProperty)) {
        throw new Exception("Array doesn't contain expected property");
      }
      return [
        'isCorrect' => $val->$expectedProperty === $expectedValue,
        'value' => $val->expectedProperty
       ];
     },
    $dogs
  );

  return $results;
}

print_r(checkResults($dogResults, 'name', 'charles'));

How to access the value of an item in an array of objects in PHP

// Functional requirements:
// We need to access the value of a single item in our PHP array of objects.
// We are going to continue to reuse the same array of Dog objects that is in our first example.
// Assumptions: $dogResults exists with 3 items.

function resultsAccess(array $list, int $key, string $property) {
  if (!isset($list[$key]) || !isset($list[$key]->$property) {
     throw new Exception("Array is missing expected Key: $key or property: $property");
  }
  return $list[$key]->$property;
}

print_r(resultsAccess($dogResults, 1, "name"));

How do you call an array of objects in PHP

how to sort an array of objects in PHP by Property

Sorting arrays of objects in PHP can be complicated. You can sort the arrays by a property or a value. You will want to create a custom sort function and use the PHP usort function. Include the use statement to pass in the desired property to sort. Inside the callback function, you can check the property, compare it and the sort it as expected.

  1. Create your custom propertySort function
  2. Include 2 parameters inside of the function: array $list, string $property
  3. Run the php usort function inside of the custom function
  4. Include a use statement for the usort function to pass in the $property parameter
  5. Run an if statement to check the property exists inside of the usort function.
  6. Run a sort comparison inside of the usort function when the property exists
  7. Return the usort results on the propertySort function
  8. Evaluate your custom function with print_r or var_dump that it meets expectation
  9. Continue processing your business requirements

function propertySort(array $list, string $property): array 
{
  return usort(
    $dogResults,
    function ($a, $b) use ($property) {
      if (!isset($a->$property) || !isset($b->$property)) {
         throw new Exception("Array is missing expected property: $property");
      }

      if ($a->$property === $b->property) {
         return 0;
      }
      
      return $a->$property > $b->$property ? 1 : -1;
    }
  )
}

print_r(propertySort($list, 'name'));

Dig Deeper into sorting an array of objects by Property in PHP

This example just is a small quick example of sorting PHP array of objects by property. There are many different use cases that you may encounter in your requirements. We wrote a full article to cover this topic in greater depth:

How to Sort Array of Objects by Property in PHP

how to Traverse and Loop through an array of PHP objects

// Function requirements:
// We need a way to traverse an array of objects in php.
// This is common whenever you need to do additional functionality on the individual objects.
// We will create a function that will update the breed property on our dog objects.
// Assumptions: $dogResults exist. This is the same content from the beginning of the article.

function traverseArrayOfObjects(array $list, callable $callbackFunction): void {
  foreach ($list as $key => $val) {
    if (is_array($val)) {
      traverseArray($val);
     }
    if (is_object($val) {
      $callbackFunction($val);
    }
  }
}

$newList = [];

traverseArrayOfObjects($dogResults, function($val) use ($newList) {
  if (isset($val->breed)) {
    $val->breed = "poodle";
    $newList[] = $val;
  }
}
     

How to compare an array of objects in PHP

You will come across situations where you need to compare multiple arrays of objects in PHP. This is much simpler than what you would expect. You can use the PHP array_diff native function to compare the 2 PHP arrays of objects. If the function returns back results then it will showcase the differences. You are able to pass in as many arrays as parameters inside of your array_diff function.

  1. Populate your initial array of objects
  2. Create additional variables with required arrays
  3. Use the php array_diff native function to compare the arrays
  4. Evaluate the array_diff function
  5. The compared arrays of objects are equal when the function returns an empty array set
  6. The function will return the differences whenever the comparisons aren’t equal across the arrays
<?php
// Function requirements:
// Compare 2 arrays of objects in PHP and create a list of differences.

/**
* print_r of arrays to compare
*
$arrayA = [
    [0] => stdClass Object
        (
            [name] => charles
            [breed] => mixed
            [father] => frank
            [mother] => susie
        )

    [1] => stdClass Object
        (
            [name] => susie
            [breed] => Border Collie
            [father] => grant
            [mother] => samantha
        )

    [2] => stdClass Object
        (
            [name] => john
            [breed] => Chihuaha
            [father] => unknown
            [mother] => samantha
        )

];
 
$arrayB = [
    [0] => stdClass Object
        (
            [name] => charles
            [breed] => mixed
            [father] => frank
            [mother] => susie
        )

    [1] => stdClass Object
        (
            [name] => susie
            [breed] => Border Collie
            [father] => grant
            [mother] => samantha
        )

    [2] => stdClass Object
        (
            [name] => cristina
            [breed] => Chihuaha
            [father] => unknown
            [mother] => samantha
        )
];
*
*/

$diffResults = array_diff($arrayA, $arrayB);

// check if there are any diffResults
if (count($diffResults) === 0) {
  echo "Both arrays are the same.";
} else {
  echo "Looks like we have differences:";
  print_r($diffResults);
}

How to merge an array of objects in PHP


/**
* print_r of arrays to merge
*
$arrayA = [
    [0] => stdClass Object
        (
            [name] => charles
            [breed] => mixed
            [father] => frank
            [mother] => susie
        )

    [1] => stdClass Object
        (
            [name] => susie
            [breed] => Border Collie
            [father] => grant
            [mother] => samantha
        )

    [2] => stdClass Object
        (
            [name] => john
            [breed] => Chihuaha
            [father] => unknown
            [mother] => samantha
        )

];
 
$arrayB = [
    [0] => stdClass Object
        (
            [name] => charles
            [breed] => mixed
            [father] => frank
            [mother] => susie
        )

    [1] => stdClass Object
        (
            [name] => susie
            [breed] => Border Collie
            [father] => grant
            [mother] => samantha
        )

    [2] => stdClass Object
        (
            [name] => cristina
            [breed] => Chihuaha
            [father] => unknown
            [mother] => samantha
        )
];
*
*/

// 1: Merge the 2 arrays together
$results = array_merge($arrayA, $arrayB);

// 2: Limit array to only unique results.
$uniqueList = array_unique($results);

print_r($uniqueList);

© 2022 Confident.Systems