user3092960
user3092960

Reputation:

How to dynamically initialize a 3d array in PHP?

I want to create a nxnxn size 3d array and fill it with 0.

Ex

if n = 3

output would be

[
  [
    [0],[0],[0]
  ],
  [
    [0],[0],[0]
  ]
  ,
  [
    [0],[0],[0]
  ]
],
[
  [
    [0],[0],[0]
  ],
  [
    [0],[0],[0]
  ]
  ,
  [
    [0],[0],[0]
  ]
],
[
  [
    [0],[0],[0]
  ],
  [
    [0],[0],[0]
  ]
  ,
  [
    [0],[0],[0]
  ]
]

Right now, I can manually do this using:

$array = array_fill(0,3,array_fill(0,3,array_fill(0,3,0)));

But, I need the array to be defined dynamically.

If n = 4, 3d array would be

$array = array_fill(0,4,array_fill(0,4,array_fill(0,4,array_fill(0,4,0)));

Upvotes: 0

Views: 74

Answers (2)

Amadan
Amadan

Reputation: 198324

function hypercube($n, $obj=0) {
  for ($i = $n; $i; $i--) {
    $obj = array_fill(0, $n, $obj);
  }
  return $obj;
}

Note: hypercube(3) will make an array that is 3x3x3. Your example shows an array that is 3x3x3x1 (because of [0]. You can do hypercube(3, array(0)) to get your sample.

Upvotes: 1

Kanti
Kanti

Reputation: 601

this should work

function getNDimensionalArray($n)
{
    $x = $n;
    $value = array();
    while ($x) {
        $value = array_fill(0, $n, $value);
        $x--;
    }
    return $value;
}

Upvotes: 1

Related Questions