How to map two arrays into an object in PHP

Updated: January 10, 2024 By: Guest Contributor Post a comment

Overview

Merging two arrays into an object in PHP can be a common task, particularly when handling key-value pair data. This tutorial will cover various methods of transforming arrays into an object by mapping keys to values using PHP.

Basic Array Mapping

Let’s start with the simplest way of mapping two arrays into an object. Assuming we have the following two associative arrays:

$keys = ['id', 'name', 'email'];
$values = [1, 'John Doe', '[email protected]'];

To convert these into an object, we can use the array_combine function followed by (object) casting:

$object = (object) array_combine($keys, $values);
var_dump($object);

Output:

object(stdClass)#1 (3) {
  ["id"]=>
  int(1)
  ["name"]=>
  string(8) "John Doe"
  ["email"]=>
  string(16) "[email protected]"
}

Custom Object Mapping

If you want more control over the result, you can create a custom class and map the arrays using a constructor or a static method. Here’s an example using a class:

class User {
    public $id;
    public $name;
    public $email;

    public function __construct($id, $name, $email) {
        $this->id = $id;
        $this->name = $name;
        $this->email = $email;
    }

    public static function fromArray($keys, $values) {
        return new self(...array_combine($keys, $values));
    }
}

$user = User::fromArray($keys, $values);
var_dump($user);

Output:

object(User)#1 (3) {
  ["id"]=>
  int(1)
  ["name"]=>
  string(8) "John Doe"
  ["email"]=>
  string(16) "[email protected]"
}

Handling Unequal Array Sizes

In a scenario where arrays are unequal in size, it’s important to handle the potential for missing data:

$keys = ['id', 'name', 'email', 'phone'];
$values = [1, 'John Doe', '[email protected]'];

We need to ensure that keys without a corresponding value are accounted for:

$filledValues = array_pad($values, count($keys), null);
$object = (object) array_combine($keys, $filledValues);
var_dump($object);

Output:

object(stdClass)#1 (4) {
  ["id"]=>
  int(1)
  ["name"]=>
  string(8) "John Doe"
  ["email"]=>
  string(16) "[email protected]"
  ["phone"]=>
  NULL
}

Using Array Functions

PHP’s array functions are powerful and can be combined to achieve more complex mappings. The array_map function, for instance, can be used with a custom function:

$keys = ['id', 'name', 'email'];
$values = [1, 'John Doe', '[email protected]'];

$combineFunc = function ($key, $value) {
    return [$key => $value];
};
$object = (object) array_reduce(array_map($combineFunc, $keys, $values), 'array_merge', []);

var_dump($object);

Output:

object(stdClass)#1 (3) {
  ["id"]=>
  int(1)
  ["name"]=>
  string(8) "John Doe"
  ["email"]=>
  string(16) "[email protected]"
}

Advanced Mapping with Array Intersect

For more advanced control, you can use array_intersect_key to filter out non-matching elements based on a set of known keys, ensuring you have a clean mapping:

$allPossibleKeys = ['id', 'name', 'email', 'age', 'phone'];
$keys = ['name', 'email'];
$values = ['John Doe', '[email protected]'];

$combinedArray = array_combine($allPossibleKeys, array_pad($values, count($allPossibleKeys), null));
$relevantData = array_intersect_key($combinedArray, array_flip($keys));
$object = (object) $relevantData;

var_dump($object);

Output:

object(stdClass)#1 (2) {
  ["name"]=>
  string(8) "John Doe"
  ["email"]=>
  string(16) "[email protected]"
}

Conclusion

Mapping arrays into an object in PHP can be performed in various ways, each suitable for different scenarios. This tutorial explored elementary to advanced techniques to proficiently accomplish this task. With the use of PHP’s built-in array functions, creating dynamic data structures is straight-forward and scalable.