17

Is there any method (that doesn't use loop or recursion) to create and fill an array with values?

To be precise, I want to have an effect of

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

But simpler.

1
  • I know this question is kinda old, but how to fill the array with range of int instead of string ? Commented Oct 17, 2012 at 10:27

5 Answers 5

40

use array_fill():

$t = array_fill(0, $n, 'val');
Sign up to request clarification or add additional context in comments.

2 Comments

Darn you beat me to it ;P For any interested, though, it turns out array_fill is up to 4x faster than the for loop version
This creates a filled array, it doesn't fill an array, two very different things.
6

I think you can use

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

to get the desired effect.

See array_pad() on php.net

Comments

5
$a = array('key1'=>'some value', 'KEY_20'=>0,'anotherKey'=>0xC0DEBABE);

/* we need to nullify whole array with keep safe keys*/

$a = array_fill_keys(array_keys($a),NULL);

var_export($a);

/*result:

array(
     'key1'=>NULL, 
     'KEY_20'=>NULL,
     'anotherKey'=>NULL
);
*/

Comments

0

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 
)

Comments

-3
$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

3 Comments

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.
Because that's the only way to fill an array without a loop. Any other method is using a loop behind the scenes regardless.
@Iznogood yes really, he asked i answered, dont burn the messenger. :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.