Php - dynamically create an array initialized with N null elements

I want to create a dynamically array with elements N (without signed N).

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 already thought about array_fill and a simple foreach .

Are there any other solutions?

+11
source share
6 answers

Actually calling array_fill :

 //... 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 } */ 
+36
source
 for ($i = 0; $i < $num_elements; $i++) { $array[$i] = null; } 
+3
source

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); } 
0
source

Simple use of array_fill sounds like the easiest solution:

 $arr = array_fill($start_at, $num_elements, null); 
0
source
 array_fill(0, $element, null); 

using this php function, you can create an array with a starting index of 0, and everyone will have a null value.

0
source

In the foreach loop, you can just use range ()

0
source

Source: https://habr.com/ru/post/892977/


All Articles