tags:

views:

56

answers:

4

I'm wondering is there any method (that doesn't use loop or recursion) to create and fill with values an array.

To be precise I want to have an effect of

$t = array();
for($i = 0; $i < $n; $i){
  $t[] = "val";
}

But simpler.

+1  A: 
$a = array(); 
$a[] = "value";
$a[] = "value";
$a[] = "value";
$a[] = "value";
$a[] = "value";
$a[] = "value";
$a[] = "value";
$a[] = "value";
$a[] = "value";
$a[] = "value";
$a[] = "value";
$a[] = "value";
$a[] = "value";
$a[] = "value";
$a[] = "value";
$a[] = "value";
$a[] = "value";
$a[] = "value";
$a[] = "value";
$a[] = "value";
$a[] = "value";    

you get the idea

Chris
How is that simpler for him? Itsthe same thing with more code and its harderto keep track of how many items you are creating. EDIT:just realised you indeed fulfill his demand ofno loops but really.
Iznogood
Because that's the only way to fill an array without a loop. Any other method is using a loop behind the scenes regardless.
Stephen
@Iznogood yes really, he asked i answered, dont burn the messenger. :-)
Chris
@Chris not shooting anyone. :-)
Iznogood
+11  A: 

use array_fill():

$t = array_fill(0, $n, 'val');
kgb
Darn you beat me to it ;PFor any interested, though, it turns out array_fill is up to 4x faster than the for loop version
Fox
+2  A: 

I think you can use

$array = array_pad(array(), $n, "val");

to get the desired effect.

See array_pad() on php.net

Frxstrem
A: 

It depends what you mean. There are functions to fill arrays, but they will all use loops behind the scenes. Assuming you are just looking to avoid loops in your code, you could use array_fill:

// Syntax: array_fill(start index, number of values; the value to fill in);
$t = array_fill(0, $n, 'val');

I.e.

<?php
    $t = array_fill(0, 10, 'val');
    print_r($t);
?>

Will give:

Array (
    [0] => val
    [1] => val
    [2] => val
    [3] => val 
    [4] => val 
    [5] => val 
    [6] => val 
    [7] => val 
    [8] => val 
    [9] => val 
)
Stephen