ハッシュテーブルのすべてのキーと値を列挙する
while( list( $key, $value ) = each( $vars ) )
{
echo "$key => $value\n";
}
可変長引数を持つ関数
function print_all() {
$count = func_num_args();
for ( $index = 0; $index < $count; $index++ ) {
echo func_get_arg( $index ) . "\n";
}
}
print_all( "test", "hoge", "puni" );
foreach構文
foreach構文を使う例。
$arr = array( "test", "hoge", "hanyaa" );
foreach ( $arr as $elem ) {
print "$elem\n";
}
whileとeachを組み合わせて使う例。
$arr = array( "test", "hoge", "hanyaa" );
while ( $elem = each( $arr ) ) {
print "$elem\n";
}
もう一度最初からループしたい時。
reset( $arr );
while ( $elem = each( $arr ) ) {
print "$elem\n";
}
正規表現にマッチするかチェック
if ( ereg( $regex, $str ) ) {
print "matched\n";
}
else {
print "not matched\n";
}
大文字小文字を無視してチェックする場合はeregi、マルチバイト文字列に対して使用する場合はmberegを用いる。
正規表現にマッチする文字列を置換する場合は、ereg_replaceを使用する。 正規表現を用いた置換処理についても、大文字小文字を無視するeregi_replace、マルチバイト対応のmberegi_replaceが存在する。
ereg_replace( $regex, $replace, $str )
ディレクトリにあるファイルを列挙する
ディレクトリにあるすべてのファイルを列挙する。 通常ファイル・ディレクトリの他に、カレントディレクトリ「.」と親ディレクトリ「..」も列挙される。
$dir = opendir( "/home/santamarta" );
while ( $filename = readdir( $dir ) ) {
echo $filename . "\n";
}
closedir( $dir );
ファイルの内容すべてを変数に代入する
ファイルの内容すべてを読み込むため、読み込もうとしているファイルのサイズが非常に大きい一方で、参照したいデータ量が少ないといった場合にはムダが多い。
$textfile = file( "sample.txt" );
while ( list( $key, $value ) = each( $textfile ) ) {
print $value;
}