PHP: Create Array and fill/initialize it with Value
Question by Guest | 2014-03-19 at 10:00
I have a PHP script in which I need some arrays.
For example the array $arr which should be preallocated with the value 1 for a length of 10 elements.
Up to now, I have initialized my array in the following way:
$arr = array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1);
However, this is very inconvenient because the arrays can become very long and it is hard to me to write the right number of elements without making any mistakes.
Isn't there any easier way for the initialization of an array in PHP?
Related Topics
Send Form Input as an Array to PHP Script
Tip | 0 Comments
JavaScript: Create and Use Arrays
Info | 0 Comments
PHP: Remove all empty elements from string array
Tip | 0 Comments
Lazarus: Load File as Byte Array and save Byte Array as File
Tutorial | 0 Comments
PHP: Fill Array with Sequence of Numbers or Characters
Tutorial | 0 Comments
PHP: Write array to individual Variables
Tutorial | 0 Comments
Delphi/Lazarus: Show Byte Array as String of HEX Values
Tip | 0 Comments
Important Note
Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.
Participate
Ask your own question or write your own article on askingbox.com. That’s how it’s done.
The function, you are searching for is called array_fill.
You can pass three parameters to array_fill:
With calling
you are doing exactly the same that you wanted to do in your example.
We are passing 0 as a start index (the first index in your array is 0), 10 as the number of fields (your array should have 10 fields) and 1 as the value. This value will be written in all 10 fields.
What is happening if we do not set the start index to 0?
Here, we are beginning with index 2 and we are inserting the value 4 for 3 times. The result is the array below.
After all, PHP ist also providing a function to fill arrays with sequences of numbers or strings - if you do not want to have the same elements in your array.
2014-03-19 at 17:10