开发者

Creating an array with $x elements in PHP

开发者 https://www.devze.com 2022-12-14 23:06 出处:网络
How would I create an array in PHP that has 开发者_StackOverflow$x empty elements? The $x is unknown and varying value. For example, if I wanted to create an array of 3 elements, I could just do:

How would I create an array in PHP that has 开发者_StackOverflow$x empty elements? The $x is unknown and varying value. For example, if I wanted to create an array of 3 elements, I could just do:

$array = array(null,null,null);

However, I don't know what $x is and there could be million elements, I need to do this automatically.


As usual with PHP there's a function for this:

  • array_fill() - Fill an array with values

Example:

$array = array_fill(0, $x, 'value');

This will create an array filled with the $x elements valued 'value' starting at array offset 0.


You can do it like this:

array_fill(0, $x, 'value')
0

精彩评论

暂无评论...
验证码 换一张
取 消