4

I have to make a two-dimensional array based on the number of lets say car parts that is submitted on a form. Is it possible to declare an array of a certain size and THEN go back and fill it?

2 Answers 2

10

PHP arrays are dynamically allocated. There's no reason to create it ahead of time. Just start using the indexes as you need them:

$myNewVar[0] = 'data';
Sign up to request clarification or add additional context in comments.

1 Comment

I disagree. Prefilling an array with empty members can avoid later having to check whether the index you want to access has been defined. I'm currently using a technique to pass an array that applies classes to twitter bootstrap elements so that, in my case, my tab pane of choice is already open when I load the page after a redirect. I could have achieved a similar effect with JS, I know, and that would have been fine. My only point is that there are cases when this kind of code is desirable.
3

You could use array_fill() for that:

$array = array_fill(1, 50, "");   // creates [1]...[50] with "" string

2 Comments

He could but he shouldn't. He's also wants to fill it with empty arrays
Multidimentional array: array_fill(1, 50, array_fill(1, 50, ""));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.