With array_fill
, I want to repeat and merge array.
Example, when I execute :
$array = array_fill(0, 2, array_merge(
['hello'],
['by']
));
var_dump($array);
I have this result :
array(2) {
[0]=>
array(2) {
[0]=>
string(5) "hello"
[1]=>
string(2) "by"
}
[1]=>
array(2) {
[0]=>
string(5) "hello"
[1]=>
string(2) "by"
}
}
But I want this result :
array(4) {
[0]=>
string(5) "hello"
[1]=>
string(2) "by"
[2]=>
string(5) "hello"
[3]=>
string(2) "by"
}
Add one more step - merge all these arrays into one:
$array = array_merge(...array_fill(0, 2, array_merge(
['hello'],
['by']
)));
Here I used a variadic function argument syntax. If your php version (older than php5.6) doesn't support it, use call_user_func_array
:
$array = call_user_func_array('array_merge', array_fill(0, 2, array_merge(
['hello'],
['by']
)));
There are many ways to do this but it's a good opportunity to show how you can do this with various PHP iterators including ArrayIterator
, InfiniteIterator
and LimitIterator
; e.g:
// create an ArrayIterator with the values you want to cycle
$values = new ArrayIterator(['hello', 'by']);
// wrap it in an InfiniteIterator to cycle over the values
$cycle = new InfiniteIterator($values);
// wrap that in a LimitIterator defining a max of four iterations
$limit = new LimitIterator($cycle,0, 4);
// then you can simply foreach over the values
$array = [];
foreach ($limit as $value) {
$array[] = $value;
}
var_dump($array);
Yields:
array(4) {
[0]=>
string(5) "hello"
[1]=>
string(2) "by"
[2]=>
string(5) "hello"
[3]=>
string(2) "by"
}
Hope this helps :)
You can use the flatten function, which will process the result of your code.
function flatten(array $ar) {
$r = array();
array_walk_recursive($ar, function($a) use (&$r) { $r[] = $a; });
return $r;
}
$array = flatten(
array_fill(0, 2, array_merge(
['hello'],
['by']
))
);
var_dump($array);
Result:
array(4) {
[0]=> string(5) "hello"
[1]=> string(2) "by"
[2]=> string(5) "hello"
[3]=> string(2) "by"
}