I just want to set the size of an array in php, without having to fill it up with any values. How do I do that?
If you want to change the size, you need to create a new array of the desired size, and then copy elements from the old array to the new array, and use the new array. In our example, arr can only hold int values. Arrays can hold primitive values, unlike ArrayList, which can only hold object values.
Size of an array If you create an array by initializing its values directly, the size will be the number of elements in it. Thus the size of the array is determined at the time of its creation or, initialization once it is done you cannot change the size of the array.
There are two common ways to get the size of an array. The most popular way is to use the PHP count() function. As the function name says, count() will return a count of the elements of an array. But how we use the count() function depends on the array structure.
You need to use a dynamically allocated array. int N; printf("Please enter size of array\n"); scanf("%d", &N); int *a = malloc(N * sizeof(int)); Then you can access it like a normal array.
Use SplFixedArray for a fixed-size array:
$array = new SplFixedArray(3); $array[0] = 1; $array[1] = 2; $array[2] = 3; $array[3] = 4; // RuntimeException
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