PHP/Laravel - Create an array of objects from two simple arrays or an associative array that combines that two
Stefan Bogdanescu
Founder & Senior Architect · 2026-06-29
Transforming an array of objects from given inputs like a PHP associative array, two simple arrays with names and classes, or two separate arrays (one for names and one for classes) can sometimes be challenging. Regardless of the input method, there are several ways to achieve your desired result using PHP and Laravel.
Using Array Mapping
In this approach, we will use Laravel's array_map() function to convert each simple array into an associative one. Here is a code example demonstrating how to combine two simple arrays (names and classes) using the array_combine() function:php
$data = array_combine($names, $classes);php
$objects = array_map(function ($item) {
return (object) [
'name' => $item,
'class' => $data[$item]
];
}, array_keys($data));Using Collection Classes
Laravel offers a built-in Collection class that provides useful methods to transform arrays into object collections or manipulate collections. We can convert our associative array into an instance of Collection class using the collect() function:php
$collection = \Illuminate\Support\Collection::make($data);php
$objects = $collection->map(function ($item) {
return (object) [
'name' => $item['someName'] ?? '',
'class' => $item['someClass'] ?? ''
];
})->map(function ($item, $key) use (&$objects) {
$objects[$key] = $item;
});