senectus
senectus

Reputation: 419

PHP - syntax for list of arrays in a single variable

I have a very complex array which contains many other very complex nested arrays. I want to break up some of the inside array groups into separate variables outside of the main variable for readability, however I'm not sure what the correct syntax is for having a list of multiple arrays in a single variable.

Wrapping the list of arrays in an array while declaring the variable isn't an option, as the variable will be inserted inside the wrapper array later on in the $array variable, so the list of arrays need to be on their own and not inside an array in the $sub_arrays variable.

<?php

$sub_arrays = array(), array(), array(); // syntax error

$array = array(
    'template' => array(
        array(
            array(),
            array(
                array(),
                // syntax error
                $sub_arrays,

                // this works, but need to be declared outside
                // array(), array(), array(),
                array(),
            )
        ),
    ),
);

print_r($array);

https://3v4l.org/2EvRA

Alternatively, separating some of the sub arrays into another .php file and using include() and return would also be an option instead of the variable? But I'm not sure about the syntax of that either.

Separation would be good not just for readability, but in case a particular group of arrays need to be reused in another instance as well.

The data is a WordPress block editor (Gutenberg) template with a lot of nested group and column blocks inside other blocks. https://developer.wordpress.org/block-editor/developers/block-api/block-templates/#nested-templates

Is this even possible to do in PHP?

Upvotes: 1

Views: 286

Answers (5)

Arth
Arth

Reputation: 13110

I'm going to attempt to simplify the problem, and define some variables as follows

$firstArray = $a; 
$subArrays = [$i, $j, $k]; 
$lastArray = $z;

where $a, $i, $j, $k, and $z are all arrays

I believe what you are trying to achieve is

$result = [$a, $i, $j, $k, $z]

without referencing the variables $a, $i, $j, $k, or $z


This can be achieved using array_merge(), providing that the arrays are not associative with duplicate keys

$result = array_merge([$firstArray], $subArrays, [$lastArray]);

Which is equivalent to

$result = array_merge([$a], [$i, $j, $k], [$z]);

By wrapping the $firstArray and $lastArray in arrays of their own, this puts them at the same level of nesting as the $subArrays before combining them all into one array


Applying this all to your original problem, and using the longer syntax, results in

$sub_arrays = array(array(), array(), array()); // Wrapped

$array = array(
    'template' => array(
        array(
            array(),
            array_merge(
                array(array()), // Wrapped
                $sub_arrays,
                array(array()), // Wrapped
            ),
        ),
    ),
);

Upvotes: 1

Florent Cardot
Florent Cardot

Reputation: 1418

Could you try this:

<?php

$sub_arrays = array(array(), array(), array()); // no syntax error

$array = array(
    'template' => array(
        array(
            array(),
            array(
                array_merge(
                array(array()),
                $sub_arrays),
                 array(),
            )
        ),
    ),
);

print_r($array);

To make it work, you have to merge your "outsider" array with the existing one. The existing one must be encapsulated in an array

Upvotes: 1

Kalimah
Kalimah

Reputation: 11437

New Answer:

Based on the comments below I think I understand the problem. I can think of two solutions to this.

First solution: The first one is the easy one, but you need PHP 7.4+ for it to work.

You can use a new feature called the slant operator (...) where by you can "unpack" one array into another. Here is the example:

<?php
$sub_arrays = [array("middle" => "array"), array(), array("external"=>"array")];

$array = array(
    'template' => array(
        array(
            array(),
            array(
               array('first'=>"array"),
                ...$sub_arrays, // use it here
                array('last'=>"array")
            )
        ),
    ),
);

print_r($array);

Live demo: https://3v4l.org/s4Q8u

Second solution: This is a bit more complex that the first one. It involves wrapping the array into a function and dynamically creating the parent array of $sub_arrays. See this:

<?php
$sub_arrays = [array("middle" => "array"), array(), array("external"=>"array")];

function create_array($sub) {
    $parent_array[] = array('first'=>"array");

    foreach($sub as $s)
    {
         $parent_array[] = $s;
    }

    $parent_array[] = array('last'=>"array");

    $array = array(
        'template' => array(
            array(
                array(),
                $parent_array
            ),
        ),
    );

    return $array;
}
print_r(create_array($sub_arrays));

Live demo: https://3v4l.org/1Vahd

I hope this helps.


Old Answer:

Your questions leaves out a lot of details to understand why you are trying to do this.

For example:

Wrapping the list of arrays in an array while declaring the variable isn't an option,

how is $sub_array inserted in $array, at what stage, are they inside a class or a function?

In any case, from what I understood, I think list is what you are looking for.

See this example:

<?php
list($a, $b) = [array('example' => 'test'), array('another' => 'array')];


var_dump($a, $b);

you can also use list for nested arrays like so:

list($a, list($b, $c)) = [array('example' => 'test'), array(array('another' => 'array'), array('I am nested'=>'array'))];

var_dump($a, $b, $c);

Upvotes: 4

Cakasim
Cakasim

Reputation: 123

You may prefer the shorter array syntax available since PHP 5.4

<?php

$arr1 = ['a', 'b', 'c'];      // >= 5.4
$arr2 = array('a', 'b', 'c'); //  < 5.4

See here for information about short syntax and arrays in general: https://www.php.net/manual/en/language.types.array.php

Using the short syntax your nested array may look like this:

<?php

$arr = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
];

The example above is a two dimensional nested array. The outer array has three elements which are arrays itself.

In order to include / require an array (or any other value) from another PHP file just do it like so $returnValue = require('./other_file.php').

In other_file.php something like this will work:

<?php

return [
    [
        [1, 2, 3],
        [4, 5, 6],
    ],
    [
        [9, 8, 7],
        [6, 5, 4],
    ],
];

Hope this helps.

Upvotes: 1

Ice76
Ice76

Reputation: 1130

Im not sure what you are asking for, but if it is how to create array variables and use them later, then here is an example. I took the WordPress example you linked in the comments. This is the template arrays broken down into sections. The structure seems to follow a pattern, hopefully this clarifies it.

$templateTop = array(
    'core/paragraph'        =>  array(
        'placeholder'           =>  'Add a root-level paragraph',
    )
);

$column1 = array(
    'core/column',
    array(),
    array(
        array(
            'core/image',
            array()
        ),
    )
);

$column2 = array(
    'core/column',
    array(),
    array(
        array(
            'core/paragraph',
            array(
                'placeholder' => 'Add a inner paragraph'
            )
        ),
    )
);

$templateColumns = array(
    'core/columns',
    array(),
    array(
        $column1, $column2
    )
);

$template = array(
    $templateTop, $templateColumns
);

Upvotes: 1

Related Questions