-2

I need to generate zeros array in php, but don't know how to generate it using php. i can do it using js.

In js array zeros code is:

for (let _i = 0; _i < 25; _i++) {
   let n = new Array(_i).fill(0)
   console.log(n);
}

Generated like this:

[]
[ 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 0, 0, 0 ]

how can i generate like this using php array?

for (let _i = 0; _i < 25; _i++) {
  let n = new Array(_i).fill(0)
  console.log(n);
}

5
  • with array_fill Commented Oct 23, 2021 at 15:10
  • how to using array_fill? Commented Oct 23, 2021 at 15:11
  • 1
    for ($i = 0; $i < 25; $i++) echo json_encode(array_fill(0, $i, 0)).PHP_EOL; 3v4l.org/AL1o3 Commented Oct 23, 2021 at 15:13
  • <?php $desiredNumber = 25; for ($i=0; $i <= $desiredNumber ; $i++) { $innerArr = array(); for( $j=0; $j <= $i; $j++ ){ array_push($innerArr, 0); } echo '['.implode(', ', $innerArr).']'; echo "<br>"; } ?> Commented Oct 23, 2021 at 15:25
  • @musabbir-mamun wow its also working <?php $desiredNumber = 25; for ($i=0; $i <= $desiredNumber ; $i++) { $innerArr = array(); for( $j=0; $j <= $i; $j++ ){ array_push($innerArr, 0); } echo '['.implode(', ', $innerArr).']'.PHP_EOL; } ?> Commented Oct 23, 2021 at 15:34

1 Answer 1

0

array_fill()

for ($i = 0; $i < 25; $i++) {
    $n = array_fill(0, $i, 0);
    echo implode(', ', $n) . PHP_EOL; // output imploded for readable reasons
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.