Nifty Looping

This looping can allow you to loop by even numbers, by 2's, 3's, odd numbers, ... etc. Up until I found this nifty looping trick, I used to use modulus' to achieve, say even numbers -- not to mention having to next some if's.

To understand this, notice in the for loop that there is a comma instead of a semicolon.

<?php
for ( $i = 0; $i++, $i < 10; $i++ )
    echo $i . '<br/>';

?>

will result in the following:

1
3
5
7
9

In addition to this, you can also loop through 2 or more variables at the same time with one for loop, as in the example below.

for ($j = "a", $k = "1"; $j <= "f", $k <= "6" ; $j++, $k++)

http://www.php.net/for »

Read files and directories

Read directory in reverse order

<?
$Results = glob( 'blah.*' );
rsort( $Results );
foreach($Results as $line){
  print($line);
}
?>

Read a directory

$directory = opendir("/path/to/directory/to/read");
while($file = readdir($directory)){
  print("$file <br />"); ### This also prints . and .. (You might filter out at least . )
}

Many times when you just read a directory, the items will not appear an any certain order. To order them alphabetically, try this,

$directory = opendir("/path/to/directory/to/read");
while($files = readdir($directory)){
  $myfile[] = $files;
}
sort($myfile);
foreach($myfile as $file){
  print("$file <br />"); ### This also prints . and .. (You might filter out at least . )
}

Once the list of files are in the array, you can manipulate the array in many other ways. One useful way is,

$reversefiles = array_reverse($myfile);

then you can perform the foreach. To filter out '.' and '..' you can use an if statement before the print like if(!eregi("^.",$file)).

Read a file

$fp = fopen("/path/to/file","r");
while(!feof($fp)){
  $line = fgets($fp);
  $line = eregi_replace("n","",$line); ### This line is optional, but useful if you want to perform
                                        ### certain eregi_replace's, for example
                                        ### eregi_replace("some text$","new text",$line);
                                        ### In that case, if you don't get rid of the n's first
                                        ### you would have to do, eregi_replace("some textn$","newtext",$line);
                                        ### first. You can also use for html output
                                        ### eregi_replace("n","<br />n",$line); ... etc
 print("$line");
}

Strings

Page Comments (Click to edit)






[Click to add or edit comments])

Please prepend comments below including a date

Design by N.Design Studio, adapted by solidGone.org (version 1.0.0)
Have a nice day.