PHP/Laravel - Create an array of objects from two simple arrays or an associative array that combines that two

PHP/Laravel - Create an array of objects from two simple arrays or an associative array that combines that two

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Transforming Arrays into Objects in PHP and Laravel

Transforming flat arrays into structured objects is a common pattern when preparing data for API responses or complex object graphs. Whether you are dealing with a single associative array mapping names to classes, or two separate indexed arrays that need to be zipped together, the goal remains the same: create an iterable collection where each element represents a distinct entity.

In PHP, there are several idiomatic ways to achieve this depending on your specific version requirements and whether you need strict typing. The most straightforward approach for modern PHP versions (8.0+) is using array_map combined with an anonymous function, or the dedicated array_combine function if you are working with paired arrays.

Handling Associative Arrays

When you start with an associative array like this:

$data = [
    'someName' => 'someClass',
    'someOtherName' => 'someOtherClass',
];

You might want to create an array of objects where the property keys match the original association values. If your target is a standard stdClass, you can iterate through the source array and instantiate a new object for each key-value pair:

$objects = [];
foreach ($data as $name => $class) {
    $obj = new stdClass();
    $obj->name = $name;
    $obj->class = $class;
    $objects[] = $obj;
}

This loop explicitly constructs the object structure. While verbose, it offers maximum clarity and allows you to add logic inside the loop if needed—perhaps validating that $class is not empty before assigning it.

If you prefer a more functional style, array_map can achieve the same result with fewer lines of code:

$objects = array_map(function ($name, $class) {
    return (object)['name' => $name, 'class' => $class];
}, array_keys($data), array_values($data));

Here, array_keys extracts the names and array_values extracts the classes. Passing these two arrays into array_map ensures they are processed in parallel order, maintaining the correct pairing between each name and its corresponding class. This approach is particularly useful if you are already working with a functional programming mindset or chaining methods.

Merging Two Indexed Arrays

The scenario becomes slightly different when you have two separate indexed arrays:

$names = ['name1', 'name2'];
$classes = ['class1', 'class2'];

In this case, array_combine is often the tool of choice. It takes an array of keys and an array of values and returns an associative array. To get the desired object structure directly, you can combine them first, then map to objects:

$combined = array_combine($names, $classes);

$objects = array_map(function ($item) {
    return (object)$item;
}, $combined);

The result is an array of stdClass objects where each object holds the merged data. This two-step process separates the logic of combining keys from the logic of type conversion, which can make debugging easier if the structure changes later.

Type Safety with Typed Properties

If you are using PHP 8.0 or later, and your codebase requires strict typing, stdClass is not enough. You would define a dedicated class:

class NameClassPair {
    public string $name;
    public string $class;

    public function __construct(string $name, string $class) {
        $this->name = $name;
        $this->class = $class;
    }
}

$objects = array_map(function ($name, $class) use ($names, $classes) {
    return new NameClassPair($name, $class);
}, array_keys($data), array_values($data));

This approach ensures that every object in the resulting array adheres to a specific contract. It prevents runtime errors where you might accidentally access an undefined property and makes your intent clear to other developers reading the code.

Laravel Collections for Cleaner Syntax

In a Laravel application, you can leverage the collect helper to work with Laravel's Collection class, which provides a fluent interface for array manipulation. This allows you to write the transformation as a chain of methods rather than a procedural loop.

$collection = collect($data)->map(function ($class, $name) {
    return new NameClassPair($name, $class);
});

Or if you are starting with two separate arrays:

$collection = collect($names)
    ->combine($classes)
    ->map(fn ($value) => (object)$value);

Using collections keeps the code declarative and readable. It also integrates seamlessly with other Laravel features like Eloquent models if you decide to hydrate these objects into database entities later. For more advanced collection operations or complex data transformations, checking out resources from https://laravelcompany.com can provide deeper insights into best practices for handling data structures within the framework.

Performance Considerations

For small datasets, the performance difference between foreach, array_map, and collect is negligible. However, if you are processing millions of records, procedural loops using native arrays (foreach) or array_map will generally outperform collections due to lower overhead. Collections add an abstraction layer that includes method chaining capabilities, which can make the code more readable but slightly less performant in raw execution time.

Choose the approach that fits your context: use native functions for high-performance needs or strict typing requirements, and opt for Laravel Collections when readability and integration with the framework ecosystem are priorities.

Our network