Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php - create,dynamically, an array initialized with N null elements

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?

like image 431
alesdario Avatar asked Jul 18 '11 08:07

alesdario


People also ask

Can we initialize array with null?

You can't: you can only make a pointer null. An array variable represents a contiguous block of memory containing values of a type that doesn't need to be a pointer type. Since no pointers are involved, you can't set it to NULL.

How do you declare a null array in PHP?

Syntax to create an empty array:$emptyArray = []; $emptyArray = array(); $emptyArray = (array) null; While push an element to the array it can use $emptyArray[] = “first”.

What are the 3 types of PHP arrays?

In PHP, there are three types of arrays: Indexed arrays - Arrays with a numeric index. Associative arrays - Arrays with named keys. Multidimensional arrays - Arrays containing one or more arrays.


1 Answers

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
}
*/
like image 141
Stefan Gehrig Avatar answered Sep 27 '22 22:09

Stefan Gehrig