How can I access a 2D array from another file on PHP?

I have a 2D array called $lang2 on one file I called ‘table.php’. After the form on table.php is submitted, it goes to another file I called ‘process.php’. I want to be able to iterate through $lang2 on the process.php file.

On ‘table.php’, I created the 2D array like this:

$lang2 = array_fill(0, count($items2), array_fill(0, 4, "e"));
$counter = 0;
foreach ($items2 as $item2) {
    $lang2[$counter][0] = $item2['localstring'];
    $lang2[$counter][1] = $item2['itemtype'];
    $lang2[$counter][2] = $item2['object_id'];
    $lang2[$counter][3] = $item2['local_id'];
    $counter++;
}

When I print the $lang2 array using print_r on ‘table.php’, the array is outputted. However, when I try to print array on ‘process.php’, my output is
Array ()

I have included my ‘table.php’ file on ‘process.php’ and have tested that other variables are able to be used from one file to another. I just can’t seem to get it to work for 2D arrays. The data from the $lang2 array comes from a database. I have tried making a 2D that doesn’t have data coming from a database and there wasn’t a difference, so I don’t think that’s the problem.

I have tried tweaking the code so that when the form is submitted, it stays on the same page, but that didn’t seem to work out. I’ve also tried making a copy of $lang2 just in case the database had something to do with it, but that didn’t make much of a difference.

What I’m expected is the array to print out like it does when I print it on the ‘table.php’ file. Something like this:

Array ( 
    [0] => Array ( 
        [0] => string1 
        [1] => 1 
        [2] => 1 
        [3] => 13 
    ) 
    [1] => Array ( 
        [0] => string2 
        [1] => 1 
        [2] => 3 
        [3] => 15 
    ) 
    [2] => Array ( 
        [0] => string3 
        [1] => 5 
        [2] => 1 
        [3] => 103 
    ) 
    [3] => Array ( 
        [0] => string4 
        [1] => 5 
        [2] => 4 
        [3] => 104 
    ) 
)

Here is a link to github with all of the code: https://github.com/SarahP15/amdb_table.git

$lang2 is created on line 164 in ‘table.php’.

I’m sorry for all the commented out bits, I’m trying to isolate the code to find what’s wrong haha

If you guys had any advice, I’d really appreciate it. Thanks!

>Solution :

On table.php, you can include the $lang2 array as a hidden input in the form using json_encode like this:

<input type="hidden" name="lang2" value="<?php echo htmlspecialchars(json_encode($lang2)); ?>">

On process.php, you can retrieve the $lang2 array from the POST data using json_decode like this:

$lang2 = json_decode($_POST['lang2'], true); // retrieve the $lang2 array from the hidden input

And add a submit action to your form like this:

<input type="submit" value="Submit">

Leave a Reply