0

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)));
1
  • Thanks @PaulCrovella. Edited my question Commented Oct 16, 2015 at 8:40

2 Answers 2

1
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.

Sign up to request clarification or add additional context in comments.

1 Comment

Works perfect. Thanks @Amadan
1

this should work

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.