14

I want to create dynamically an array with N (without knowking N) elements.

Something like a function

public function create_array($num_elements){

     .....
}

that return me something like

//call the function.... 
create_array(3);

//and the output is: 
array{
   0 => null
   1 => null
   2 => null
}

I've already thought about array_fill and a simple foreach loop.

Are there any other solutions?

4
  • do yourself and everyone else a favour and just use array_fill Commented Jul 18, 2011 at 8:56
  • is array_fill the best solution for you? Commented Jul 18, 2011 at 9:03
  • 1
    array_fill is a core function - nothing will be faster than that. What would you expect from the "best solution"? Commented Jul 18, 2011 at 9:18
  • The solution which works best. If array_fill is the function which works faster and easiest, probably it's the best solution (personal opinion). Commented Jul 18, 2011 at 10:44

6 Answers 6

50

Actually a call to array_fill should be sufficient:

//...
public function create_array($num_elements){
    return array_fill(0, $num_elements, null);
}
//..

var_dump(create_array(3));
/*
array(3) {
  [0]=> NULL
  [1]=> NULL
  [2]=> NULL
}
*/
Sign up to request clarification or add additional context in comments.

Comments

3
for ($i = 0; $i < $num_elements; $i++) {
    $array[$i] = null;
}

1 Comment

this is the most obvious solution, and the best (for my test) since the other solutions are not faster than this!
1
array_fill(0, $element, null);

using this php function, you can create array with starting index 0, and all will have null value.

Comments

0

Simple use of array_fill sounds like the easiest solution:

$arr = array_fill($start_at, $num_elements, null);

Comments

0

Do array_fill and foreach not work?

Of course, the simplest solution that comes to mind is

function create_array($num_elements) {
    $r = array();
    for ($i = 0; $i < $num_elements; $i++)
        $r[] = null;
    return $r;
}

array_fill should also work:

function create_array($num_elements) {
    return array_fill(0, $num_elements, null);
}

Comments

0

In foreach loop you can simply use range()

1 Comment

Unfortunately, range doesn't give us a way to set a default value like array_fill does. Close, though!

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.