开发者

cannot access the array using php

开发者 https://www.devze.com 2023-02-18 03:36 出处:网络
i have created an array using php something like this $array1=array() for($i=0;$i<5;$i++) { $array1[$i]=somevalue;

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++)
  {
开发者_如何学Go    print_r($array1[$y]);
  }
}

it does not print the value.


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]);
}


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


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);
}


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);


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++)
0

精彩评论

暂无评论...
验证码 换一张
取 消