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.
=> 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 .
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.
As usual with PHP there's a function for this:
array_fill()
- Fill an array with valuesExample:
$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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With