Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

My loop is only returning one value

Tags:

php

The issue here is that when I do print_r after I create the array with $picnameoutput it prints the array as you will see in the screenshot.

Later after I run the for loop and echo it just to see the output it only gives me 1 value and I can't figure out why it picks that value, it is not even the first one in the array.

Very Frustrated.

Here is my code

<?php
  $largedir = 'images/headshots/large';
  $large = scandir($largedir);

  $picnameoutput = preg_grep("/adam.*/", $large); 
  print_r($picnameoutput);

  for ($i=0; $i<count($picnameoutput); $i++); {
  echo "$picnameoutput[$i]";
  }
?>

And here is a screenshot so you can see what I mean

enter image description here

like image 972
GrooveChampion Avatar asked Sep 01 '11 20:09

GrooveChampion


2 Answers

You have a semicolon ; after for() before bracket. Remove it.

So

for ($i=0; $i<count($picnameoutput); $i++); {
echo "$picnameoutput[$i]";
}

becomes

for ($i=0; $i<count($picnameoutput); $i++) {
    echo "$picnameoutput[$i]";
}

however I would recommend to use foreach() instead

foreach ($picnameoutput as $pic) {
    echo $pic;
}

which is pretty easy to use and even faster than your for loop

like image 146
genesis Avatar answered Oct 20 '22 00:10

genesis


You have a semi-colon after the for, so your code is executed like:

for ($i=0; $i<count($picnameoutput); $i++) {
   ; // Do nothing
}
{
  echo "$picnameoutput[$i]";
}

Also, it could be written shorter as

echo implode('', glob('images/headshots/large/adam*'));
like image 20
phihag Avatar answered Oct 20 '22 01:10

phihag