Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In php how do I set the size of an array?

Tags:

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?

like image 776
dave Avatar asked Apr 06 '11 00:04

dave


People also ask

How do you set the size of an array?

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.

Can I change the size of an array?

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.

What is the size of array in PHP?

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.

How do I let the user choose the size of an array?

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.


1 Answers

Use SplFixedArray for a fixed-size array:

$array = new SplFixedArray(3); $array[0] = 1; $array[1] = 2; $array[2] = 3; $array[3] = 4; // RuntimeException 
like image 173
netcoder Avatar answered Oct 18 '22 10:10

netcoder