Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

40,026 questions

51,982 answers

573 users

How to create and set values to a 3d array in PHP

1 Answer

0 votes
function initializeArray(&$array, $x, $y, $z) {
    for ($i = 0; $i < $x; $i++) {
        for ($j = 0; $j < $y; $j++) {
            for ($k = 0; $k < $z; $k++) {
                $array[$i][$j][$k] = $i + $j + $k; // Initialization
            }
        }
    }
}

function printArray($array, $x, $y, $z) {
    for ($i = 0; $i < $x; $i++) {
        for ($j = 0; $j < $y; $j++) {
            for ($k = 0; $k < $z; $k++) {
                echo $array[$i][$j][$k] . " ";
            }
            echo "\n";
        }
    }
}

$x = 2;
$y = 3;
$z = 4;
$array = array_fill(0, $x, array_fill(0, $y, array_fill(0, $z, 0))); // Create a 3D array

initializeArray($array, $x, $y, $z);
printArray($array, $x, $y, $z);

 
 
/*
run:
 
0 1 2 3 
1 2 3 4 
2 3 4 5 
1 2 3 4 
2 3 4 5 
3 4 5 6
 
*/

 



answered Apr 21, 2025 by avibootz
...