3 Push elements in a multidimensional array PHP code examples

Last Updated on

CraftyTechie is reader-supported. When you buy through links on our site, we may earn an affiliate commission.

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 code example

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’ 🙂

PHP Fundamentals Recommendations

This article is part of our content on PHP Fundamentals. It includes the core concepts that build upon the foundation of writing high-quality PHP code. If you are looking to grow your PHP development abilities. Check out the following recommended affiliate resources.

We do make a commission if you do choose to buy through our links. It is one of the ways that help support our mission here at FuelingPHP.

Book: Fundamentals of Web Development

This book is for you if you are starting to learn how to build websites. It is more than just an “intro to programming” book. You will learn the concepts and tips on what goes into creating a high-quality website. Today’s websites are more than text on a screen. They are highly complex applications that encourage user experience. Learn the fundamentals of good web development with this book.

Check it out on Amazon

Book: Programming in PHP (O’Reilly)

O’Reilly should not need any introduction. They are the top publishers when it comes to books on programming and technology. This book fits well within their vast library. If you are newer to the PHP language or want to keep a solid reference by your side. I highly recommend this book for your collection.

Check it out on Amazon

Book: Design Patterns in PHP

I highly recommend this book to any intermediate-level web developer. It takes the theories and best practices of writing high-quality code via design patterns and applies them to PHP. It is a great resource to take your career to the next level

Check it out on Amazon

Video Course: PHP Fundamentals (Pluralsight)

Want to quickly learn PHP? This PHP Fundamentals course is ideal for beginner PHP developers. It is a deep dive into the concepts, structures and well “fundamentals” of PHP development. It includes high-quality video & interactive resources that teach you really fast. I highly recommend this if you are getting started in your PHP journey.

Click here for a 10-day free trial to Pluralsight

Complete Learning Path: Web Development (Pluralsight)

You should definitely check out this learning path from Pluralsight. They have a huge list of video courses, training, and interactive lessons on growing your web development career. You get access to the full library of hundreds of resources for a single monthly subscription. It truly is like Netflix for your career.

Click here to see details (10-day free trial included)

Want more reviews? Check out our HUGE list of Beginner Web Development Books We’ve Researched and Reviewed for you.

Pushing Elements in a Multidimensional PHP Array

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.

Did you find this article helpful?

Join the best weekly newsletter where I deliver content on building better web applications. I curate the best tips, strategies, news & resources to help you develop highly-scalable and results-driven applications.

Build Better Web Apps

I hope you're enjoying this article.

Get the best content on building better web apps delivered to you.