Sling Academy
Home/PHP/How to map two arrays into an object in PHP

How to map two arrays into an object in PHP

Last updated: January 10, 2024

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.

Next Article: PHP: How to remove all falsy values from an array

Previous Article: 3 Ways to remove duplicates from an array in PHP

Series: PHP Data Structure Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array