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?
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.
Syntax to create an empty array:$emptyArray = []; $emptyArray = array(); $emptyArray = (array) null; While push an element to the array it can use $emptyArray[] = “first”.
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.
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
}
*/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With