0

i have created an array using php something like this

$array1=array()

for($i=0;$i<5;$i++)
{
  $array1[$i]=somevalue;
  for($y=0;$y<$i;$y++)
  {
    print_r($array1[$y]);
  }
}

it does not print the value.

8
  • Can you please write your array? your array on top has no vallues.. ;) Commented Mar 18, 2011 at 11:46
  • its a new array which i am creating Commented Mar 18, 2011 at 11:48
  • something like this doesn't help us find your actual problem. Are you getting any errors? have you got all error reporting turned on. What is your actual code? Commented Mar 18, 2011 at 11:48
  • are you aware the second loop will be printing the array many times even when [0] is set but the rest are not? Commented Mar 18, 2011 at 11:49
  • 2
    there are some syntax errors in your code. If it's the real code you posted here, you have to correct them and it will work. if you're actually running another code, you have to post it here. Commented Mar 18, 2011 at 11:49

5 Answers 5

1

If nothing else, you should move the inner loop out:

for($i=0;$i<5;$i++)
{
    $array1[$i]=somevalue;
}

for($y=0;$y<5;$y++)
{
    print_r($array1[$y]);
}
Sign up to request clarification or add additional context in comments.

2 Comments

$i is not going to be available outside the first for loop
@Belinda: Copy/paste programming is bad :) Thanks for the catch.
1

I just ran this code, the only change i made was putting a semicolon in the first line ;)

<?php

$array1=array();

for($i=0;$i<5;$i++)
{
  $array1[$i]="abcd";
  for($y=0;$y<$i;$y++)
  {
    print_r($array1[$y]);
  }
}

?>

Output: abcdabcdabcdabcdabcdabcdabcdabcdabcdabcd

Comments

1

Based on @Jon's answer:

$array1 = array();
for($i=0;$i<5;$i++)
{
    $array1[$i]=somevalue;
}

$count = count($array1);

for($y=0;$y<$count;$y++)
{
    print_r($array1[$y]);
}

You can put the count function in the for loop, but that's bad practice. Also, if you are trying to get the value of EVERY value in the array, try a foreach instead.

$array1 = array();
for($i=0;$i<5;$i++)
{
    $array1[$i]=somevalue;
}
foreach($array1 as $value)
{
  print_r($value);
}

Comments

0

Because of the way how print_r works, it is silly to put it inside a loop, this will give you actual output and is error free :).

$array1=array();

for($i=0;$i<5;$i++)
{
  $array1[$i]='somevalue';
}
print_r($array1);

Comments

0
for($y=0;$y<$i;$y++)

Your display loop isn't displaying the entry you've just added as $array[$i], because you're looping $y while it's less than $i

for($y=0;$y<=$i;$y++)

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.