Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an array with $x elements in PHP

Tags:

arrays

php

How would I create an array in PHP that has $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.

like image 592
Tower Avatar asked Dec 20 '09 12:12

Tower


People also ask

What does => mean in PHP array?

=> is the separator for associative arrays. In the context of that foreach loop, it assigns the key of the array to $user and the value to $pass .

How do you create an array for loops?

For Loop to Traverse Arrays. We can use iteration with a for loop to visit each element of an array. This is called traversing the array. Just start the index at 0 and loop while the index is less than the length of the array.


2 Answers

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.

like image 124
preinheimer Avatar answered Oct 20 '22 16:10

preinheimer


You can do it like this:

array_fill(0, $x, 'value')
like image 38
hanse Avatar answered Oct 20 '22 18:10

hanse