1

im trying to create an array from a loop in PHP.

I want the array to end up something like $array(100,100,100,100), this is my code:

$x = 0; 
while($x < 5){ 
$array[$x] = 100; 
$x++; 
} 

echo $array[0];

It outputs 1 instead of 100. Can someone tell me where i'm going wrong.

3
  • 1
    For me, copy/pasted straight into the PHP interpreter it works correctly. PHP 5.3.8 Commented Oct 22, 2011 at 22:45
  • 1
    Works like a charm for me: codepad.org/9U8Yfqfp. Are you sure that the $array is empty before inserting the new values? Commented Oct 22, 2011 at 22:46
  • 2
    A for loop would be more appropriate than while here for ($x = 0; $x < 5; $x++) since you know both the starting and ending values of $x. i.e. since you have a predetermined number of iterations. Commented Oct 22, 2011 at 22:46

3 Answers 3

5

Even though it works perfectly for me, you should be initialising the variable beforehand.

$array = array();

For example, if $array is non-empty string, you will see the output of 1.

Sign up to request clarification or add additional context in comments.

3 Comments

could you explain why it happens with the non empty string? I could imagine that it results in 11111 by casting 100 to string and taking the first char, but can't imagine why it is 1.
@NikiC - It's because it's setting a character in the string, and not a new array value, and $array[0] will be the first "character" in the string; see my second demo.
ah, got it, $array[0] is output, so it takes only the first 1.
3

You can just use the predefined array_fill function for that:

$array = array_fill(0, 5, 100);

Comments

2

The other answers pretty much cover this. I would, however, recommend you use a for loop for this instead of a while loop if you're going to use a loop rather than a function to do it.

$array = array();
for($x=0; $x<5; $x++) {
    $array[$x] = 100;
}

In fact, you could make this even shorter.

$array = array();
for($x=0; $x<5; $array[$x++]=100);

It's perfectly valid to have a for loop statement instead of a block. And blocks can go anywhere too; they don't need an if statement, for loop, while loop, or whatever, before them.

Comments

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.