How to push elements in a multidimensional array in PHP

Summary:

There are 2 options to push multidimensional arrays in PHP. You can use a recursive approach or the array_walk function. Check out the article for examples.

Push elements in a multidimensional array in PHP

PHP arrays are dynamic, meaning that they expand as new values are added. Dynamic arrays are a huge improvement over static arrays with a pre-defined length specified during initialisation.

push elements in a multidimensional array in PHP

Linear or one-dimensional arrays are fairly easy to understand. Contrary to this,  multidimensional arrays can be tricky. These arrays can include many sub-arrays, and the structure may not be consistent. Similarly, sometimes pushing onto a multidimensional array in PHP is a challenge. 

This article focuses on how to push elements in a multidimensional array in PHP.

Push elements in a multidimensional array in PHP using loops

PHP loops are the first thing that comes to mind when dealing with arrays. Here’s a two-dimensional array that includes information about some employees working in a tech firm.

$employees_records = [
    ['Name' => 'Alex', 'Title' => 'Web Developer (Front-End)'],
    ['Name' => 'Brian', 'Title' => 'Web Developer (Back-End)'],
    ['Name' => 'Catherine', 'Title' => 'UI/UX Designer'],
    ['Name' => 'Diana', 'Title' => 'Software Quality Assurance'],
    ['Name' => 'Franklin', 'Title' => 'DevOps Engineer']
];

So, the task is to add ‘Ids’ to every employee. Let’s see how to add to the multidimensional array given.

foreach($employees_records as $k => &$v)
{
    $v['Id'] = $k + 1; //Creates an Id key and assigns it a value.
}

Here is a two-step breakdown of this example code.

  1. The foreach loop iterates the multidimensional array.
  2. The $v[‘Id’] adds an ‘Id’ key to every sub-array.

Also, & before the $v is necessary, or the change won’t reflect in the array. Following is the output of this example.

    [['Name' => 'Alex', 'Title' => 'Web Developer (Front-End)', 'Id' => 1],
    ['Name' => 'Brian', 'Title' => 'Web Developer (Back-End)', 'Id' => 2],
    ['Name' => 'Catherine', 'Title' => 'UI/UX Designer, 'Id' => 3],
    ['Name' => 'Diana', 'Title' => 'Software Quality Assurance', 'Id' => 4],
    ['Name' => 'Franklin', 'Title' => 'DevOps Engineer', 'Id' => 5]]

Push elements in a multidimensional array in PHP with array_walk

PHP array_walk apply a callback function to every member of an array. Although the foreach loop performs better than the array_walk function, it is just another way to achieve a similar goal. One advantage of this function is reusability, as it supports the callback function.

Anyway, here’s another array having information about some students.

$students_records = [
    ['Id' => '2204', 'Name' => 'Peter', 'Subjects' => ['Data structures and Algorithms']],
    ['Id' => '3211', 'Name' => 'James', 'Subjects' => ['Computer Architecture']],
    ['Id' => '5409', 'Name' => 'Riley', 'Subjects' => ['Calculus-II']],
];

The goal is to add pre-requisite courses to the ‘Subjects’ sub-array. The subjects mapping array is given as.

$prerequisites = [
    'Data structures and Algorithms' => 'Introduction to Programming',
    'Computer Architecture' => 'Digital logic design',
    'Calculus-II' => 'Calculus-I'
];

Here’s the example of pushing onto multidimensional array PHP using the array_walk function.

array_walk($students_records, function(&$value, $key) use ($prerequisites) {
    $subject = $value['Subjects'][0]; //Gets the name of the subject.
    $prerequisite_subject = $prerequisites[$subject]; //Finds the prerequisite subject
    $value['Subjects'][] = $prerequisite_subject; //Push it to the array
});

The breakdown of this example is as follows.

  1. The array_walk takes a callback function and refers the $prerequisites from outer scope.
  2. The $subject indexes the sub-array to get the course name from ‘Subjects’.
  3. A prerequisite course is found from the mapping array, $prerequisites.
  4. Adds the prerequisite to the ‘Subjects’ sub-array.

The array_walk function syntax can be confusing. So, to get a better understanding see the array_walk function by FuelingPHP.

Following is the output of the example.

[
['Id' => '2204', 'Name' => 'Peter', 'Subjects' => ['Data structures and Algorithms', 'Introduction to Programming']],
['Id' => '3211', 'Name' => 'James', 'Subjects' => ['Computer Architecture', 'Digital logic design]],
['Id' => '5409', 'Name' => 'Riley', 'Subjects' => ['Calculus-II', 'Calculus-I']]
];

Quick Note

PHP array_push pushes one or more elements to an array. Use array_push when there multiple elements to push. Use the example syntax for a single element push to avoid the overhead of a function call.

Push elements in a multidimensional array PHP using recursive approach

Recursion is handy for dealing with multidimensional arrays. Recursive algorithms access deeply nested structures efficiently and are generally independent of the array dimensions. Let’s look at what we have here and then go with the recursive approach. 

$hotels = [
    ['Name' => 'Atlanta Inn', 'Features'=> [
        'RoomsTypes' => ['Single-Bed','Double-Bed', 'Luxury'],
        'Facilities' => ['Free Wi-Fi', '24/7 Room Service']
    ]],
    ['Name' => 'Aurora', 'Features'=> [
        'RoomsTypes' => ['Double-Bed', 'Luxury'],
        'Facilities' => ['24/7 Room Service', 'Swimming Pool']
    ]],
    ['Name' => 'Aurora', 'Features'=> [
        'RoomsTypes' => ['Double-Bed', 'Luxury'],
        'Facilities' => ['24/7 Room Service', 'Swimming Pool']
    ]],
];

So, there is a hotel array with a fairly complex makeup. The goal here is to add ‘Free Wi-Fi’ to the ‘Facilities’ in the ‘Features’ key. The ‘Features’ is yet again two-dimensional. Let’s do that through recursion.

Following is the example of adding elements to a multidimensional array in PHP using recursion.

function recurse_hotels(&$hotels, $add)
{
    foreach($hotels as $k => &$v)
    {
        if($k == 'Facilities')
        {
            $v[] =  $add;
        }
 
        else if(gettype($v) == 'array') {
            recurse_hotels($v, $add);
        }
 
    }
   
}
 
}

The example is intuitive and fairly simple yet super helpful. It adds to the multidimensional array without needing any nested loops. The hotels now include ‘Free Wi-Fi’ in the ‘Facilities’ 🙂

Conclusion

This article includes examples of how to add elements to a multidimensional array in PHP. Loops and recursions are always first-in-line approaches to deal with arrays. Recursion is the most robust approach. PHP array_walk function also helps to append to multidimensional array in PHP.

That’s all about this article. Hopefully, you’ve enjoyed it. Learn more about PHP through intuitive and in-depth articles and tutorials at FuelingPHP.

Want to learn more about PHP?

We have many fun articles related to PHP. You can explore these to learn more about PHP.


Article Categories

Article Tags

© 2022 Confident.Systems