How to use flatten() helper function to convert a multi-dimensional array into a single array

Avatar
C

Callum Davies

Senior Backend Engineer••
7825Views
5mRead
0Reactions

Hello, In this tutorial, I would like to show you, how you can convert a multi-dimensional array into a single array. Sometimes, we fetch some problems when we fetch multi-relational data. We can use flatter() helper, to easily convert a more readable array. Let me show how to do that,

Example:

use Illuminate\Support\Arr;

        $array = [
        'name' => 'english',
        'languages' =>
            'programming'=> [
                'php',
                'java',
                'c++',
                'c#',
            ],
        ];

        $flattened = Arr::flatten($array);

Output:

=> [
     "english",
    "php",
    "java",
    "c",
    "c++",
  ]

Hope, it will help you.

Connect with KoderSolution 🚀

Master modern software engineering, scalable architectures, and advanced backend systems.

What's your setup?How does your production stack handle background jobs? Are you using Redis with Horizon, or cloud queues like AWS SQS?
Callum Davies
C
Written by•Senior Backend Engineer

Callum Davies

PHP & Laravel practitioner since v5.4. Big believer in thin controllers, explicit return types, and boring modular architecture that doesn't page you on weekends.

React to this article

Recommended Articles

View all articles