$string = '\n'; $string = 'Jon \'Maddog\' Orwant'; $string = 'Jon "Maddog" Orwant'; $string = "\n"; $string = "Jon \"Maddog\" Orwant"; $string = "Jon 'Maddog' Orwant"; $a =
"This is a multiline
here document";
$a = <<<EOF
This is a multiline here document
terminated by EOF on a line by itself
EOF;
$value = substr($string, $offset, $count);
$value = substr($string, $offset);
$string = substr_replace($string, $newstring, $offset, $count);
$string = substr_replace($string, $newtail, $offset);
list($leading, $s1, $s2, $trailing) =
array_values(unpack("A5a/x3/A8b/A8c/A*d", $data);
preg_match_all ("/.{5}/", $data, $f, PREG_PATTERN_ORDER);
$fivers = $f[0];
$chars = $string;
$string = "This is what you have";
$first = substr($string, 0, 1); $start = substr($string, 5, 2); $rest = substr($string, 13); $last = substr($string, -1); $end = substr($string, -4); $piece = substr($string, -8, 3); $string = "This is what you have";
print $string;
$string = substr_replace($string, "wasn't", 5, 2);
$string = substr_replace($string, "ondrous", -12);
$string = substr_replace($string, "", 0, 1);
$string = substr_replace($string, "", -10); if (preg_match("/pattern/", substr($string, -10)) {
print "Pattern matches in last 10 characters\n";
}
$string=(substr_replace(preg_replace("/is/", "at", substr($string,0,5)),0,5);
$a = "make a hat";
list($a[0], $a[strlen($a)-1]) = Array(substr($a,-1), substr($a,0,1));
print $a;
$a = "To be or not to be";
$b = unpack("x6/A6a", $a); print $b['a'];
$b = unpack("x6/A2b/X5/A2c", $a); print $b['b']."\n".$b['c']."\n";
function cut2fmt() {
$positions = func_get_args();
$template = '';
$lastpos = 1;
foreach($positions as $place) {
$template .= "A" . ($place - $lastpos) . " ";
$lastpos = $place;
}
$template .= "A*";
return $template;
}
$fmt = cut2fmt(8, 14, 20, 26, 30);
print "$fmt\n";
$a = $b?$b:$c;
$x || $x=$y;
$a = defined($b) ? $b : $c;
$foo = $bar || $foo = "DEFAULT VALUE";
$dir = array_shift($_SERVER['argv']) || $dir = "/tmp";
$dir = $_SERVER['argv'][0] || $dir = "/tmp";
$dir = defined($_SERVER['argv'][0]) ? array_shift($_SERVER['argv']) : "/tmp";
$dir = count($_SERVER['argv']) ? $_SERVER['argv'][0] : "/tmp";
$count[$shell?$shell:"/bin/sh"]++;
$user = $_ENV['USER']
|| $user = $_ENV['LOGNAME']
|| $user = posix_getlogin()
|| $user = posix_getpwuid(posix_getuid())[0]
|| $user = "Unknown uid number $<";
$starting_point || $starting_point = "Greenwich";
count($a) || $a = $b; $a = count($b) ? $b : $c;
list($VAR1, $VAR2) = array($VAR2, $VAR1);
$temp = $a;
$a = $b;
$b = $temp;
$a = "alpha";
$b = "omega";
list($a, $b) = array($b, $a); list($alpha, $beta, $production) = Array("January","March","August");
list($alpha, $beta, $production) = array($beta, $production, $alpha);
$num = ord($char);
$char = chr($num);
$char = sprintf("%c", $num); printf("Number %d is character %c\n", $num, $num);
$ASCII = unpack("C*", $string);
eval('$STRING = pack("C*", '.implode(',',$ASCII).');');
$ascii_value = ord("e"); $character = chr(101); printf("Number %d is character %c\n", 101, 101);
$ascii_character_numbers = unpack("C*", "sample");
print explode(" ",$ascii_character_numbers)."\n";
eval('$word = pack("C*", '.implode(',',$ascii_character_numbers).');');
$word = pack("C*", 115, 97, 109, 112, 108, 101); print "$word\n";
$hal = "HAL";
$ascii = unpack("C*", $hal);
foreach ($ascii as $val) {
$val++; }
eval('$ibm = pack("C*", '.implode(',',$ascii).');');
print "$ibm\n";
$array = preg_split('//', $string ,-1, PREG_SPLIT_NO_EMPTY);
for ($offset = 0; preg_match('/(.)/', $string, $matches, 0, $offset) > 0; $offset++) {
}
$seen = array();
$string = "an apple a day";
foreach (str_split($string) as $char) {
$seen[$char] = 1;
}
$keys = array_keys($seen);
sort($keys);
print "unique chars are: " . implode('', $keys)) . "\n";
unique chars are: adelnpy
$seen = array();
$string = "an apple a day";
for ($offset = 0; preg_match('/(.)/', $string, $matches, 0, $offset) > 0; $offset++) {
$seen[$matches[1]] = 1;
}
$keys = array_keys($seen);
sort($keys);
print "unique chars are: " . implode('', $keys) . "\n";
unique chars are: adelnpy
$sum = 0;
foreach (unpack("C*", $string) as $byteval) {
$sum += $byteval;
}
print "sum is $sum\n";
$sum = array_sum(unpack("C*", $string));
$handle = @fopen($argv[1], 'r');
$checksum = 0;
while (!feof($handle)) {
$checksum += (array_sum(unpack("C*", fgets($handle))));
}
$checksum %= pow(2,16) - 1;
print "$checksum\n";
<?php
$delay = 1;
if (preg_match('/(.)/', $argv[1], $matches)) {
$delay = $matches[1];
array_shift($argv);
};
$handle = @fopen($argv[1], 'r');
while (!feof($handle)) {
foreach (str_split(fgets($handle)) as $char) {
print $char;
usleep(5000 * $delay);
}
}
$revchars = strrev($string);
$revwords = implode(" ", array_reverse(explode(" ", $string)));
$string = 'Yoda said, "can you see this?"';
$allwords = explode(" ", $string);
$revwords = implode(" ", array_reverse($allwords));
print $revwords . "\n";
this?" see you "can said, Yoda
$revwords = implode(" ", array_reverse(explode(" ", $string)));
$revwords = implode(" ", array_reverse(preg_split("/(\s+)/", $string)));
$word = "reviver";
$is_palindrome = ($word === strrev($word));
% php -r 'while (!feof(STDIN)) { $word = rtrim(fgets(STDIN)); if ($word == strrev($word) && strlen($word) > 5) print $word; }' < /usr/dict/words
$text = preg_replace('/\$(\w+)/e', '$$1', $text);
list($rows, $cols) = Array(24, 80);
$text = 'I am $rows high and $cols long';
$text = preg_replace('/\$(\w+)/e', '$$1', $text);
print $text;
$text = "I am 17 years old";
$text = preg_replace('/(\d+)/e', '2*$1', $text);
$text = preg_replace('/\$(\w+)/e','isset($$1)?$$1:\'[NO VARIABLE: $$1]\'', $text);
$big = strtoupper($little);
$little = strtolower($big);
$big = ucfirst($little);
$little = strtolower(substr($big, 0, 1)) . substr($big, 1);
$beast = "dromedary";
$capit = ucfirst($beast); $capall = strtoupper($beast); $caprest = strtolower(substr($beast, 0, 1)) . substr(strtoupper($beast), 1); $text = "thIS is a loNG liNE";
$text = ucwords(strtolower($text));
print $text;
This Is A Long Line
if (strtoupper($a) == strtoupper($b)) { print "a and b are the same\n";
}
<?php
function randcase($word) {
return rand(0, 100) < 20 ? ucfirst($word) : lcfirst($word);
}
function lcfirst($word) {
return strtolower(substr($word, 0, 1)) . substr($word, 1);
}
while (!feof(STDIN)) {
print preg_replace("/(\w)/e", "randcase('\\1')", fgets(STDIN));
}
echo $var1 . func() . $var2; $answer = "STRING ${[ VAR EXPR ]} MORE STRING";
$phrase = "I have " . ($n + 1) . " guanacos.";
$output = wordwrap($str, $width, $break, $cut);
<?php
$input = "Folding and splicing is the work of an editor, " .
"not a mere collection of silicon " .
"and " .
"mobile electrons!";
$columns = 20;
print str_repeat("0123456789", 2) . "\n";
print wordwrap(' ' . $input, $columns - 3, "\n ") . "\n";
print wordwrap(str_replace("\n", " ", file_get_contents('php://stdin')));
while(!feof(STDIN)) {
print wordwrap(str_replace("\n", " ", stream_get_line(STDIN, 0, "\n\n")));
print "\n\n";
}
$var = preg_replace('/([CHARLIST])/', '\\\$1', $var);
$var = preg_replace('/([CHARLIST])/', '$1$1', $var);
$var = preg_replace('/%/', '%%', $var);
$string = 'Mom said, "Don\'t do that."';
$string = preg_replace('/([\'"])/', '\\\$1', $string);
$string = 'Mom said, "Don\'t do that."';
$string = preg_replace('/([\'"])/', '$1$1', $string);
$string = preg_replace('/([^A-Z])/', '\\\$1', $string);
$string = "this is\\ a\\ test\\!";
$string = preg_replace('/(\W)/', '\\\$1', 'is a test!');
$string = trim($string);
while (!feof(STDIN)) {
print ">" . substr(fgets(STDIN), 0, -1) . "<\n";
}
$string = preg_replace('/\s+/', ' ', $string); $string = trim($string);
$string = preg_replace('/\s+/', ' ', $string);
function sub_trim($string) {
$string = trim($string);
$string = preg_replace('/\s+/', ' ', $string);
return $string;
}
$code = soundex($string);
$phoned_words = metaphone("Schwern");
function getpwent() {
$pwents = array();
$handle = fopen("passwd", "r");
while (!feof($handle)) {
$line = fgets($handle);
if (preg_match("/^#/", $line)) continue;
$cols = explode(":", $line);
$pwents[$cols[0]] = $cols[4];
}
return $pwents;
}
print "Lookup user: ";
$user = rtrim(fgets(STDIN));
if (empty($user)) exit;
$name_code = soundex($user);
$pwents = getpwent();
foreach($pwents as $username => $fullname) {
preg_match("/(\w+)[^,]*\b(\w+)/", $fullname, $matches);
list(, $firstname, $lastname) = $matches;
if ($name_code == soundex($username) ||
$name_code == soundex($lastname) ||
$name_code == soundex($firstname))
{
printf("%s: %s %s\n", $username, $firstname, $lastname);
}
}
<?php
$data = <<<DATA
analysed=> analyzed
built-in=> builtin
chastized => chastised
commandline => command-line
de-allocate => deallocate
dropin => drop-in
hardcode=> hard-code
meta-data => metadata
multicharacter => multi-character
multiway=> multi-way
non-empty => nonempty
non-profit => nonprofit
non-trappable => nontrappable
pre-define => predefine
preextend => pre-extend
re-compiling=> recompiling
reenter => re-enter
turnkey => turn-key
DATA;
$scriptName = $argv[0];
$verbose = ($argc > 1 && $argv[1] == "-v" && array_shift($argv));
$change = array();
foreach (preg_split("/\n/", $data) as $pair) {
list($in, $out) = preg_split("/\s*=>\s*/", trim($pair));
if (!$in || !$out) continue;
$change[$in] = $out;
}
if (count($argv) > 1) {
$orig = $argv[1] . ".orig";
copy($argv[1], $orig);
$input = fopen($orig, "r");
$output = fopen($argv[1], "w");
} else if ($scriptName != "-") {
$input = STDIN;
trigger_error("$scriptName: Reading from stdin\n", E_USER_WARNING);
}
$ln = 1;
while (!feof($input)) {
$line = fgets($input);
foreach ($change as $in => $out) {
$line = preg_replace("/$in/", $out, $line, -1, $count);
if ($count > 0 && $verbose) {
fwrite(STDERR, "$in => $out at $argv[1] line $ln.\n");
}
}
@fwrite($output, $line);
$ln++;
}
<?php
$data = <<<DATA
analysed=> analyzed
built-in=> builtin
chastized => chastised
commandline => command-line
de-allocate => deallocate
dropin => drop-in
hardcode=> hard-code
meta-data => metadata
multicharacter => multi-character
multiway=> multi-way
non-empty => nonempty
non-profit => nonprofit
non-trappable => nontrappable
pre-define => predefine
preextend => pre-extend
re-compiling=> recompiling
reenter => re-enter
turnkey => turn-key
DATA;
$scriptName = $argv[0];
$verbose = ($argc > 1 && $argv[1] == "-v" && array_shift($argv));
if (count($argv) > 1) {
$orig = $argv[1] . ".orig";
copy($argv[1], $orig);
$input = fopen($orig, "r");
$output = fopen($argv[1], "w");
} else if ($scriptName != "-") {
$input = STDIN;
trigger_error("$scriptName: Reading from stdin\n", E_USER_WARNING);
}
$config = array();
foreach (preg_split("/\n/", $data) as $pair) {
list($in, $out) = preg_split("/\s*=>\s*/", trim($pair));
if (!$in || !$out) continue;
$config[$in] = $out;
}
$ln = 1;
while (!feof($input)) {
$i = 0;
preg_match("/^(\s*)(.*)/", fgets($input), $matches);
fwrite($output, $matches[1]);
foreach (preg_split("/(\s+)/", $matches[2], -1, PREG_SPLIT_DELIM_CAPTURE) as $token) {
fwrite($output, ($i++ & 1) ? $token : (array_key_exists($token, $config) ? $config[$token] : $token));
}
}
while (!feof($input)) {
$i = 0;
preg_match("/^(\s*)(.*)/", fgets($input), $matches); fwrite($output, $matches[1]);
foreach (preg_split("/(\s+)/", $matches[2]) as $token) { fwrite($output, (array_key_exists($token, $config) ? $config[$token] : $token) . " ");
}
fwrite($output, "\n");
}
under
$s = '12.345';
preg_match('/\D/', $s) && die("has nondigits\n");
preg_match('/^\d+$/', $s) || die("not a natural number\n");
preg_match('/^-?\d+$/', $s) || die("not an integer\n");
preg_match('/^[+-]?\d+$/', $s) || die("not an integer\n");
preg_match('/^-?\d+\.?\d*$/', $s) || die("not a decimal\n");
preg_match('/^-?(?:\d+(?:\.\d*)?|\.\d+)$/', $s) || die("not a decimal\n");
preg_match('/^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/', $s) || die("not a C float\n");
function getnum($s)
{
sscanf($s, "%D", $number); return isset($number) ? $number : 0;
}
echo getnum(123) . "\n"; echo getnum(0xff) . "\n"; echo getnum(044) . "\n";
echo getnum('x') . "\n";
if ($float_1 == $float_2)
{
; }
$cmp = strcmp('123456789.123456789123456789', '123456789.123456789123456788');
$precision = 5; if (bccomp('1.111117', '1.111116', $precision))
{
; }
$precision = 6;
if (bccomp('1.111117', '1.111116', $precision))
{
; }
$wage = 536;
$week = $wage * 40;
printf("One week's wage is: $%.2f\n", $week / 100);
$rounded = round($unrounded, $precision);
$format = '%[width].[prec]f';
$rounded = sprintf($format, $unrounded);
$a = 0.255; $b = round($a, 2);
echo "Unrounded: {$a}\nRounded: {$b}\n";
$a = 0.255; $b = sprintf('%.2f', $a);
echo "Unrounded: {$a}\nRounded: {$b}\n";
$a = 0.255;
printf("Unrounded: %.f\nRounded: %.2f\n", $a, $a);
echo "number\tint\tfloor\tceil\n";
foreach(array(3.3, 3.5, 3.7, -3.3) as $number)
{
printf("%.1f\t%.1f\t%.1f\t%.1f\n", $number, (int) $number, floor($number), ceil($number));
}
$num = bindec('0110110');
$binstr = decbin(54);
foreach (range($X, $Y) as $i)
{
; }
foreach (range($X, $Y, 7) as $i)
{
; }
for ($i = $X; $i <= $Y; $i++)
{
; }
for ($i = $X; $i <= $Y; $i += 7)
{
; }
echo 'Infancy is:'; foreach(range(0, 2) as $i) echo " {$i}\n";
echo 'Toddling is:'; foreach(range(3, 4) as $i) echo " {$i}\n";
echo 'Childhood is:'; foreach(range(5, 12) as $i) echo " {$i}\n";
$roman = Numbers_Roman::toNumeral($arabic);
$arabic = Numbers_Roman::toNumber($roman);
$roman_fifteen = Numbers_Roman::toNumeral(15);
$arabic_fifteen = Numbers_Roman::toNumber($roman_fifteen);
printf("Roman for fifteen is: %s\n", $roman_fifteen);
printf("Arabic for fifteen is: %d\n", $arabic_fifteen);
$random = rand($lowerbound, $upperbound);
$random = rand($x, $y);
function make_password($chars, $reqlen)
{
$len = strlen($chars);
for ($i = 0; $i < $reqlen; $i++) $password .= substr($chars, rand(0, $len), 1);
return $password;
}
$chars = 'ABCDEfghijKLMNOpqrstUVWXYz'; $reqlen = 8;
$password = make_password($chars, $reqlen);
while (TRUE)
{
$seed = (int) fgets(STDIN);
if (!empty($seed)) break;
}
srand($seed);
mt_srand($saved_random_value + microtime() * 1000003);
mt_srand(($saved_random_value + hexdec(substr(md5(microtime()), -8))) & 0x7fffffff);
$truly_random_value = mt_rand();
function random() { return (float) rand() / (float) getrandmax(); }
function gaussian_rand()
{
$u1 = 0.0; $u2 = 0.0; $g1 = 0.0; $g2 = 0.0; $w = 0.0;
do
{
$u1 = 2.0 * random() - 1.0; $u2 = 2.0 * random() - 1.0;
$w = $u1 * $u1 + $u2 * $u2;
} while ($w > 1.0);
$w = sqrt((-2.0 * log($w)) / $w); $g2 = $u1 * $w; $g1 = $u2 * $w;
return $g1;
}
$mean = 25.0; $sdev = 2.0;
$salary = gaussian_rand() * $mean + $sdev;
printf("You have been hired at: %.2f\n", $salary);
/ them if needed
function deg2rad_($deg) { return ($deg / 180.0) * M_PI; }
function rad2deg_($rad) { return ($rad / M_PI) * 180.0; }
printf("%f\n", deg2rad_(180.0));
printf("%f\n", deg2rad(180.0));
function degree_sin($deg) { return sin(deg2rad($deg)); }
$rad = deg2rad(380.0);
printf("%f\n", sin($rad));
printf("%f\n", degree_sin(380.0));
function my_tan($theta) { return sin($theta) / cos($theta); }
$theta = 3.7;
printf("%f\n", my_tan($theta));
printf("%f\n", tan($theta));
$value = 100.0;
$log_e = log($value);
$log_10 = log10($value);
function log_base($base, $value) { return log($value) / log($base); }
$answer = log_base(10.0, 10000.0);
printf("log(10, 10,000) = %f\n", $answer);
$a = new Math_Matrix(array(array(3, 2, 3), array(5, 9, 8)));
$b = new Math_Matrix(array(array(4, 7), array(9, 3), array(8, 1)));
echo $a->toString() . "\n";
echo $b->toString() . "\n";
$c = $a->clone_();
$c->multiply($b);
echo $c->toString() . "\n";
$a = new Math_Complex(3, 5);
$b = new Math_Complex(2, -2);
$c = Math_ComplexOp::mult($a, $b);
echo $c->toString() . "\n";
$d = new Math_Complex(3, 4);
$r = Math_ComplexOp::sqrt($d);
echo $r->toString() . "\n";
$dec = 867;
$hex = sprintf('%x', $dec);
$oct = sprintf('%o', $dec);
$dec = 0;
$hex = '363';
sscanf($hex, '%x', $dec);
$dec = 0;
$oct = '1543';
sscanf($oct, '%o', $dec);
$number = 0;
printf('Gimme a number in decimal, octal, or hex: ');
sscanf(fgets(STDIN), '%D', $number);
printf("%d %x %o\n", $number, $number, $number);
function commify_series($s) { return number_format($s, 0, '', ','); }
$hits = 3456789;
printf("Your website received %s accesses last month\n", commify_series($hits));
function commify($s)
{
return strrev(preg_replace('/(\d\d\d)(?=\d)(?!\d*\.)/', '${1},', strrev($s)));
}
$hits = 3456789;
echo commify(sprintf("Your website received %d accesses last month\n", $hits));
function pluralise($value, $root, $singular='' , $plural='s')
{
return $root . (($value > 1) ? $plural : $singular);
}
$duration = 1;
printf("It took %d %s\n", $duration, pluralise($duration, 'hour'));
printf("%d %s %s enough.\n", $duration, pluralise($duration, 'hour'),
pluralise($duration, '', 'is', 'are'));
$duration = 5;
printf("It took %d %s\n", $duration, pluralise($duration, 'hour'));
printf("%d %s %s enough.\n", $duration, pluralise($duration, 'hour'),
pluralise($duration, '', 'is', 'are'));
function plural($singular)
{
$s2p = array('/ss$/' => 'sses', '/([psc]h)$/' => '${1}es', '/z$/' => 'zes',
'/ff$/' => 'ffs', '/f$/' => 'ves', '/ey$/' => 'eys',
'/y$/' => 'ies', '/ix$/' => 'ices', '/([sx])$/' => '$1es',
'$' => 's');
foreach($s2p as $s => $p)
{
if (preg_match($s, $singular)) return preg_replace($s, $p, $singular);
}
}
foreach(array('mess', 'index', 'leaf', 'puppy') as $word)
{
printf("%6s -> %s\n", $word, plural($word));
}
format
function dateOffset()
{
static $tbl = array('sec' => 1, 'min' => 60, 'hou' => 3600, 'day' => 86400, 'wee' => 604800);
$delta = 0;
foreach (func_get_args() as $arg)
{
$kv = explode('=', $arg);
$delta += $kv[1] * $tbl[strtolower(substr($kv[0], 0, 3))];
}
return $delta;
}
function dateInterval($intvltype, $timevalue)
{
static $tbl = array('sec' => 1, 'min' => 60, 'hou' => 3600, 'day' => 86400, 'wee' => 604800);
return (int) round($timevalue / $tbl[strtolower(substr($intvltype, 0, 3))]);
}
$today = getdate();
printf("Today is day %d of the current year\n", $today['yday']);
$today = localtime();
printf("Today is day %d of the current year\n", $today[7]);
$today = localtime(time(), TRUE);
printf("Today is day %d of the current year\n", $today['tm_yday']);
define(SEP, '-');
$today = getdate();
$day = $today['mday'];
$month = $today['mon'];
$year = $today['year'];
$sep = SEP;
echo "Current date is: {$year}{$sep}{$month}{$sep}{$day}\n";
echo 'Current date is: ' . $year . SEP . $month . SEP . $day . "\n";
$today = localtime(time(), TRUE);
$day = $today['tm_mday'];
$month = $today['tm_mon'] + 1;
$year = $today['tm_year'] + 1900;
printf("Current date is: %4d%s%2d%s%2d\n", $year, SEP, $month, SEP, $day);
$format = 'Y' . SEP . 'n' . SEP . 'd';
$today = date($format);
echo "Current date is: {$today}\n";
$sep = SEP;
$today = strftime("%Y$sep%m$sep%d");
echo "Current date is: {$today}\n";
$timestamp = mktime($hour, $min, $sec, $month, $day, $year);
$timestamp = gmmktime($hour, $min, $sec, $month, $day, $year);
$dmyhms = getdate();
$dmyhms = getdate($timestamp);
$day = $dmyhms['mday'];
$month = $dmyhms['mon'];
$year = $dmyhms['year'];
$hours = $dmyhms['hours'];
$minutes = $dmyhms['minutes'];
$seconds = $dmyhms['seconds'];
$when = $now + $difference;
$then = $now - $difference;
$now = mktime(0, 0, 0, 8, 6, 2003);
$diff1 = dateOffset('day=1'); $diff2 = dateOffset('weeks=2');
echo 'Today is: ' . date('Y-m-d', $now) . "\n";
echo 'One day in the future is: ' . date('Y-m-d', $now + $diff1) . "\n";
echo 'Two weeks in the past is: ' . date('Y-m-d', $now - $diff2) . "\n";
$birthtime = mktime(3, 45, 50, 1, 18, 1973);
$interval = dateOffset('day=55', 'hours=2', 'min=17', 'sec=5');
$then = $birthtime + $interval;
printf("Birthtime is: %s\nthen is: %s\n", date(DATE_RFC1123, $birthtime), date(DATE_RFC1123, $then));
$hr = 3; $min = 45; $sec = 50; $mon = 1; $day = 18; $year = 1973;
$yroff = 0; $monoff = 0; $dayoff = 55; $hroff = 2; $minoff = 17; $secoff = 5;
$birthtime = mktime($hr, $min, $sec, $mon, $day, $year, TRUE);
$year = date('Y', $birthtime) + $yroff;
$mon = date('m', $birthtime) + $monoff;
$day = date('d', $birthtime) + $dayoff;
$hr = date('H', $birthtime) + $hroff;
$min = date('i', $birthtime) + $minoff;
$sec = date('s', $birthtime) + $secoff;
$then = mktime($hr, $min, $sec, $mon, $day, $year, TRUE);
printf("Birthtime is: %s\nthen is: %s\n", date(DATE_RFC1123, $birthtime), date(DATE_RFC1123, $then));
$birthtime = mktime(3, 45, 50, 1, 18, 1973);
$birthtime = strtotime('1/18/1973 03:45:50');
$then = strtotime('+55 days 2 hours 17 minutes 2 seconds', $birthtime);
printf("Birthtime is: %s\nthen is: %s\n", date(DATE_RFC1123, $birthtime), date(DATE_RFC1123, $then));
$birthtime = new DateTime('1/18/1973 03:45:50');
$then = new DateTime('1/18/1973 03:45:50');
$then->modify('+55 days 2 hours 17 minutes 2 seconds');
printf("Birthtime is: %s\nthen is: %s\n", $birthtime->format(DATE_RFC1123), $then->format(DATE_RFC1123));
$interval_seconds = $recent - $earlier;
$bree = strtotime('16 Jun 1981, 4:35:25');
$nat = strtotime('18 Jan 1973, 3:45:50');
$bree = mktime(4, 35, 25, 6, 16, 1981, TRUE);
$nat = mktime(3, 45, 50, 1, 18, 1973, TRUE);
$difference = $bree - $nat;
printf("There were %d seconds between Nat and Bree\n", $difference);
printf("There were %d weeks between Nat and Bree\n", dateInterval('weeks', $difference));
printf("There were %d days between Nat and Bree\n", dateInterval('days', $difference));
printf("There were %d hours between Nat and Bree\n", dateInterval('hours', $difference));
printf("There were %d minutes between Nat and Bree\n", dateInterval('mins', $difference));
$today = getdate();
$weekday = $today['wday'];
$monthday = $today['mday'];
$yearday = $today['yday'];
$weeknumber = (int) round($yearday / 7.0);
$weeknumber = strftime('%U') + 1;
define(SEP, '/');
$day = 16;
$month = 6;
$year = 1981;
$timestamp = mktime(0, 0, 0, $month, $day, $year);
$date = getdate($timestamp);
$weekday = $date['wday'];
$monthday = $date['mday'];
$yearday = $date['yday'];
$weeknumber = (int) round($yearday / 7.0);
$weeknumber = strftime('%U', $timestamp) + 1;
$sep = SEP;
echo "{$month}{$sep}{$day}{$sep}{$year} was a {$date['weekday']} in week {$weeknumber}\n";
echo $month . SEP . $day . SEP . $year . ' was a ' . $date['weekday']
. ' in week ' . $weeknumber . "\n";
$timestamp = strtotime('1998-06-03'); echo strftime('%Y-%m-%d', $timestamp) . "\n";
print_r(strptime('1998-06-03', '%Y-%m-%d'));
$darr = strptime('1998-06-03', '%Y-%m-%d');
if (!empty($darr))
{
print_r($darr);
if (empty($darr['unparsed']))
{
if (checkdate($darr['tm_mon'] + 1, $darr['tm_mday'], $darr['tm_year'] + 1900))
echo "Parsed date verified as correct\n";
else
echo "Parsed date failed verification\n";
}
else
{
echo "Date string parse not complete; failed components: {$darr['unparsed']}\n";
}
}
else
{
echo "Date string could not be parsed\n";
}
$ts = 1234567890;
date('Y/m/d', $ts);
date('Y/m/d', mktime($h, $m, $s, $mth, $d, $y, $is_dst));
date('Y/m/d');
$ts = 1234567890;
strftime('%Y/%m/%d', $ts);
strftime('%Y/%m/%d', mktime($h, $m, $s, $mth, $d, $y, $is_dst));
strftime('%Y/%m/%d');
$t = strftime('%a %b %e %H:%M:%S %z %Y', mktime(3, 45, 50, 1, 18, 73, TRUE));
echo "{$t}\n";
$t = strftime('%a %b %e %H:%M:%S %z %Y', gmmktime(3, 45, 50, 1, 18, 73));
echo "{$t}\n";
$t = strftime('%A %D', strtotime('18 Jan 1973, 3:45:50'));
echo "{$t}\n";
$t = strftime('%A %D', mktime(3, 45, 50, 1, 18, 73, TRUE));
echo "{$t}\n";
$before = microtime();
$line = fgets(STDIN);
$elapsed = microtime() - $before;
printf("You took %.3f seconds\n", $elapsed);
define(NUMBER_OF_TIMES, 100);
define(SIZE, 500);
for($i = 0; $i < NUMBER_OF_TIMES; $i++)
{
$arr = array();
for($j = 0; $j < SIZE; $j++) $arr[] = rand();
$begin = microtime();
sort($arr);
$elapsed = microtime() - $begin;
$total_time += $elapsed;
}
printf("On average, sorting %d random numbers takes %.5f seconds\n", SIZE, $total_time / (float) NUMBER_OF_TIMES);
sleep(1);
usleep(250000);
$nested = array('this', 'that', 'the', 'other');
$nested = array('this', 'that', array('the', 'other')); print_r($nested);
$tune = array('The', 'Star-Spangled', 'Banner');
$a = array('quick', 'brown', 'fox');
$a = escapeshellarg('Why are you teasing me?');
$lines = <<<END_OF_HERE_DOC
The boy stood on the burning deck,
it was as hot as glass.
END_OF_HERE_DOC;
$bigarray = array_map('rtrim', file('mydatafile'));
$banner = 'The mines of Moria';
$banner = escapeshellarg('The mines of Moria');
$name = 'Gandalf';
$banner = "Speak {$name}, and enter!";
$banner = 'Speak ' . escapeshellarg($name) . ' and welcome!';
$his_host = 'www.perl.com';
$host_info = `nslookup $his_host`;
$cmd = 'ps ' . posix_getpid(); $perl_info = `$cmd`;
$shell_info = `ps $$`;
$banner = array('Costs', 'only', '$4.95');
$banner = array_map('escapeshellarg', split(' ', 'Costs only $4.95'));
$brax = split(' ', '( ) < > { } [ ]');
$rings = split(' ', 'Nenya Narya Vilya');
$tags = split(' ', 'LI TABLE TR TD A IMG H1 P');
$sample = split(' ', 'The vertical bar | looks and behaves like a pipe.');
function commify_series($list)
{
$n = str_word_count($list); $series = str_word_count($list, 1);
if ($n == 0) return NULL;
if ($n == 1) return $series[0];
if ($n == 2) return $series[0] . ' and ' . $series[1];
return join(', ', array_slice($series, 0, -1)) . ', and ' . $series[$n - 1];
}
echo commify_series('red') . "\n";
echo commify_series('red yellow') . "\n";
echo commify_series('red yellow green') . "\n";
$mylist = 'red yellow green';
echo 'I have ' . commify_series($mylist) . " marbles.\n";
function commify_series($arr)
{
$n = count($arr); $sepchar = ',';
foreach($arr as $str)
{
if (strpos($str, ',') === false) continue;
$sepchar = ';'; break;
}
if ($n == 0) return NULL;
if ($n == 1) return $arr[0];
if ($n == 2) return $arr[0] . ' and ' . $arr[1];
return join("{$sepchar} ", array_slice($arr, 0, -1)) . "{$sepchar} and " . $arr[$n - 1];
}
$lists = array(
array('just one thing'),
split(' ', 'Mutt Jeff'),
split(' ', 'Peter Paul Mary'),
array('To our parents', 'Mother Theresa', 'God'),
array('pastrami', 'ham and cheese', 'peanut butter and jelly', 'tuna'),
array('recycle tired, old phrases', 'ponder big, happy thoughts'),
array('recycle tired, old phrases', 'ponder big, happy thoughts', 'sleep and dream peacefully'));
foreach($lists as $arr)
{
echo 'The list is: ' . commify_series($arr) . ".\n";
}
$arr[] = 'one';
array_unshift($arr, 'one', 'two', 'three');
array_push($arr, 'one', 'two', 'three');
unset($arr[$idx1], $arr[$idx2], $arr[$idx3]);
$item = array_shift($arr);
$item = array_pop($arr);
function what_about_the_array()
{
global $people;
echo 'The array now has ' . count($people) . " elements\n";
echo 'The index value of the last element is ' . (count($people) - 1) . "\n";
echo 'Element #3 is ' . $people[3] . "\n";
}
$people = array('Crosby', 'Stills', 'Nash', 'Young');
what_about_the_array();
array_pop($people);
what_about_the_array();
foreach ($list as $item) {
}
$env = $_ENV;
ksort($env);
foreach ($env as $key => $value) {
echo "{$key}={$value}\n";
}
$keys = array_keys($_ENV);
sort($keys);
foreach ($keys as $key) {
echo "{$key}={$_ENV[$key]}\n";
}
foreach ($all_users as $user) {
$disk_space = get_usage($user);
if ($disk_space > MAX_QUOTA) {
complain($user);
}
}
$array = array(1, 2, 3);
$newarray = array();
foreach ($array as $item) {
$newarray[] = $item - 1;
}
print_r($newarray);
$array = array(1, 2, 3);
foreach ($array as &$item) {
$item--;
}
print_r($array);
foreach($array as $item)
{
; }
foreach($array as &$item)
{
; }
$arraylen = count($array);
for($i = 0; $i < $arraylen; $i++)
{
; }
$fruits = array('Apple', 'Raspberry');
foreach($fruits as &$fruit)
{
echo "{$fruit} tastes good in a pie.\n";
}
$fruitlen = count($fruits);
for($i = 0; $i < $fruitlen; $i++)
{
echo "{$fruits[$i]} tastes good in a pie.\n";
}
$rogue_cats = array('Blackie', 'Goldie', 'Silkie');
$namelist['felines'] =& $rogue_cats;
foreach($namelist['felines'] as &$cat)
{
$cat .= ' [meow]';
}
foreach($namelist['felines'] as $cat)
{
echo "{$cat} purrs hypnotically.\n";
}
echo "---\n";
foreach($rogue_cats as $cat)
{
echo "{$cat} purrs hypnotically.\n";
}
$unique = array_unique($array);
$unique = array_values(array_unique($array));
$unique = array_keys(array_flip($array));
foreach($list as $item)
{
if (!isset($seen[$item]))
{
$seen[$item] = TRUE;
$unique[] = $item;
}
}
foreach($list as $item)
{
$seen[$item] || (++$seen[$item] && ($unique[] = $item));
}
function some_func($item)
{
; }
foreach($list as $item)
{
$seen[$item] || (++$seen[$item] && some_func($item));
}
foreach(array_slice(preg_split('/\n/', `who`), 0, -1) as $user_entry)
{
$user = preg_split('/\s/', $user_entry);
$ucnt[$user[0]]++;
}
ksort($ucnt);
echo "users logged in:\n";
foreach($ucnt as $user => $cnt)
{
echo "\t{$user} => {$cnt}\n";
}
$a = array('c', 'a', 'b', 'd');
$b = array('c', 'a', 'b', 'e');
$diff = array_diff($a, $b); $diff = array_diff($b, $a);
$diff = array_values(array_diff($a, $b)); $diff = array_values(array_diff($b, $a));
$a = array('k1' => 11, 'k2' => 12, 'k4' => 14);
$b = array('k1' => 11, 'k2' => 12, 'k3' => 13);
foreach($b as $item => $value) { $seen[$item] = 1; }
foreach($a as $item => $value) { if (!$seen[$item]) $aonly[] = $item; }
foreach($a as $item => $value) { if (!$seen[$item]) $aonly[$item] = $value; }
$hash['key1'] = 1;
$hash['key2'] = 2;
$hash = array_combine(array('key1', 'key2'), array(1, 2));
$seen = array_slice($b, 0);
$seen = array_combine(array_keys($b), array_fill(0, count($b), 1));
$a = array(1, 3, 5, 6, 7, 8);
$b = array(2, 3, 5, 7, 9);
$union = array_values(array_unique(array_merge($a, $b))); $isect = array_values(array_intersect($a, $b)); $diff = array_values(array_diff($a, $b));
$arr1 = array('c', 'a', 'b', 'd');
$arr2 = array('c', 'a', 'b', 'e');
$new = array_merge($arr1, $arr2);
$members = array('Time', 'Flies');
$initiates = array('An', 'Arrow');
$members = array_merge($members, $initiates);
$members = array('Time', 'Flies');
$initiates = array('An', 'Arrow');
array_splice($members, 2, 0, array_merge(array('Like'), $initiates));
echo join(' ', $members) . "\n";
array_splice($members, 0, 1, array('Fruit'));
array_splice($members, -2, 2, array('A', 'Banana'));
echo join(' ', $members) . "\n";
$reversed = array_reverse($array);
foreach(array_reverse($array) as $item)
{
; }
for($i = count($array) - 1; $i >= 0; $i--)
{
; }
sort($array);
$array = array_reverse($array);
rsort($array);
function popN(&$arr, $n)
{
$ret = array_slice($arr, -($n), $n);
$arr = array_slice($arr, 0, count($arr) - $n);
return $ret;
}
function shiftN(&$arr, $n)
{
$ret = array_slice($arr, 0, $n);
$arr = array_slice($arr, $n);
return $ret;
}
$front = shiftN($array, $n);
$end = popN($array, $n);
$friends = array('Peter', 'Paul', 'Mary', 'Jim', 'Tim');
list($this_, $that) = shiftN($friends, 2);
echo "{$this_} {$that}\n";
$beverages = array('Dew', 'Jolt', 'Cola', 'Sprite', 'Fresca');
$pair = popN($beverages, 2);
echo join(' ', $pair) . "\n";
$found = FALSE;
foreach($array as $item)
{
if (!$criterion) continue;
$match = $item;
$found = TRUE;
break;
}
if ($found)
{
; }
else
{
; }
function predicate($element)
{
if (criterion) return TRUE;
return FALSE;
}
$match = array_slice(array_filter($array, 'predicate'), 0, 1);
if ($match)
{
; }
else
{
; }
class Employee
{
public $name, $age, $ssn, $salary;
public function __construct($name, $age, $ssn, $salary, $category)
{
$this->name = $name;
$this->age = $age;
$this->ssn = $ssn;
$this->salary = $salary;
$this->category = $category;
}
}
$employees = array(
new Employee('sdf', 27, 12345, 47000, 'Engineer'),
new Employee('ajb', 32, 12376, 51000, 'Programmer'),
new Employee('dgh', 31, 12355, 45000, 'Engineer'));
function array_update($arr, $lambda, $updarr)
{
foreach($arr as $key) $lambda($updarr, $key);
return $updarr;
}
function highest_salaried_engineer(&$arr, $employee)
{
static $highest_salary = 0;
if ($employee->category == 'Engineer')
{
if ($employee->salary > $highest_salary)
{
$highest_salary = $employee->salary;
$arr[0] = $employee;
}
}
}
$highest_salaried_engineer = array_update($employees, 'highest_salaried_engineer', array());
echo 'Highest paid engineer is: ' . $highest_salaried_engineer[0]->name . "\n";
function predicate($element)
{
if (criterion) return TRUE;
return FALSE;
}
$matching = array_filter($list, 'predicate');
$bigs = array_filter($nums, create_function('$n', 'return $n > 1000000;'));
function is_pig($user)
{
$user_details = preg_split('/(\s)+/', $user);
return $user_details[5] > 1e7;
}
$pigs = array_filter(array_slice(preg_split('/\n/', `who -u`), 0, -1), 'is_pig');
$matching = array_filter(array_slice(preg_split('/\n/', `who`), 0, -1),
create_function('$user', 'return preg_match(\'/^gnat /\', $user);'));
class Employee
{
public $name, $age, $ssn, $salary;
public function __construct($name, $age, $ssn, $salary, $category)
{
$this->name = $name;
$this->age = $age;
$this->ssn = $ssn;
$this->salary = $salary;
$this->category = $category;
}
}
$employees = array(
new Employee('sdf', 27, 12345, 47000, 'Engineer'),
new Employee('ajb', 32, 12376, 51000, 'Programmer'),
new Employee('dgh', 31, 12355, 45000, 'Engineer'));
$engineers = array_filter($employees,
create_function('$employee', 'return $employee->category == "Engineer";'));
$unsorted = array(7, 12, -13, 2, 100, 5, 1, -2, 23, 3, 6, 4);
sort($unsorted); rsort($unsorted);
asort($unsorted); arsort($unsorted);
natsort($unsorted);
function ascend($left, $right) { return $left > $right; }
function descend($left, $right) { return $left < $right; }
usort($unsorted, 'ascend'); usort($unsorted, 'descend');
uasort($unsorted, 'ascend'); uasort($unsorted, 'descend');
function kill_process($pid)
{
if (!posix_kill($pid, 0)) return;
posix_kill($pid, 15); sleep(1);
posix_kill($pid, 9); }
function pid($pentry)
{
$p = preg_split('/\s/', trim($pentry));
return $p[0];
}
$processes = array_map('pid', array_slice(preg_split('/\n/', `ps ax`), 1, -1));
sort($processes);
echo join(' ,', $processes) . "\n";
echo 'Enter a pid to kill: ';
if (($pid = trim(fgets(STDIN))))
kill_process($pid);
function comparator($left, $right)
{
; }
$ordered = array_slice($unordered);
usort($ordered, 'comparator');
function compute($value)
{
; }
$unordered = array(5, 3, 7, 1, 4, 2, 6);
foreach($unordered as $value)
{
$precomputed[compute($value)] = $value;
}
$ordered_precomputed = array_slice($precomputed, 0); ksort($ordered_precomputed);
$ordered = array_values($ordered_precomputed);
function array_update($arr, $lambda, $updarr)
{
foreach($arr as $key) $lambda($updarr, $key);
return $updarr;
}
function accum(&$arr, $value)
{
$arr[compute($value)] = $value;
}
function compute($value)
{
; }
$unordered = array(5, 3, 7, 1, 4, 2, 6);
$precomputed = array_update($unordered, 'accum', array());
$ordered_precomputed = array_slice($precomputed, 0); ksort($ordered_precomputed);
$ordered = array_values($ordered_precomputed);
class Employee
{
public $name, $age, $ssn, $salary;
public function __construct($name, $age, $ssn, $salary)
{
$this->name = $name;
$this->age = $age;
$this->ssn = $ssn;
$this->salary = $salary;
}
}
$employees = array(
new Employee('sdf', 27, 12345, 47000),
new Employee('ajb', 32, 12376, 51000),
new Employee('dgh', 31, 12355, 45000));
$ordered = array_slice($employees, 0);
usort($ordered, create_function('$left, $right', 'return $left->name > $right->name;'));
$sorted_employees = array_slice($employees, 0);
usort($sorted_employees, create_function('$left, $right', 'return $left->name > $right->name;'));
$bonus = array(12376 => 5000, 12345 => 6000, 12355 => 0);
foreach($sorted_employees as $employee)
{
echo "{$employee->name} earns \${$employee->salary}\n";
}
foreach($sorted_employees as $employee)
{
if (($amount = $bonus[$employee->ssn]))
echo "{$employee->name} got a bonus of: \${$amount}\n";
}
$sorted = array_slice($employees, 0);
usort($sorted, create_function('$left, $right', 'return $left->name > $right->name || $left->age != $right->age;'));
function get_pw_entries()
{
function normal_users_only($e)
{
$entry = split(':', $e); return $entry[2] > 100 && $entry[2] < 32768;
}
foreach(array_filter(file('/etc/passwd'), 'normal_users_only') as $entry)
$users[] = split(':', trim($entry));
return $users;
}
$users = get_pw_entries();
usort($users, create_function('$left, $right', 'return $left[0] > $right[0];'));
foreach($users as $user) echo "{$user[0]}\n";
$names = array('sdf', 'ajb', 'dgh');
$sorted = array_slice($names, 0);
usort($sorted, create_function('$left, $right', 'return substr($left, 1, 1) > substr($right, 1, 1);'));
$strings = array('bbb', 'aa', 'c');
$sorted = array_slice($strings, 0);
usort($sorted, create_function('$left, $right', 'return strlen($left) > strlen($right);'));
function array_update($arr, $lambda, $updarr)
{
foreach($arr as $key) $lambda($updarr, $key);
return $updarr;
}
function accum(&$arr, $value)
{
$arr[strlen($value)] = $value;
}
$strings = array('bbb', 'aa', 'c');
$temp = array_update($strings, 'accum', array());
ksort($temp);
$sorted = array_values($temp);
function array_update($arr, $lambda, $updarr)
{
foreach($arr as $key) $lambda($updarr, $key);
return $updarr;
}
function accum(&$arr, $value)
{
if (preg_match('/(\d+)/', $value, $matches))
$arr[$matches[1]] = $value;
}
$fields = array('b1b2b', 'a4a', 'c9', 'ddd', 'a');
$temp = array_update($fields, 'accum', array());
ksort($temp);
$sorted_fields = array_values($temp);
array_unshift($a1, array_pop($a1)); array_push($a1, array_shift($a1));
function grab_and_rotate(&$arr)
{
$item = $arr[0];
array_push($arr, array_shift($arr));
return $item;
}
$processes = array(1, 2, 3, 4, 5);
while (TRUE)
{
$process = grab_and_rotate($processes);
echo "Handling process {$process}\n";
sleep(1);
}
$arr = array(1, 2, 3, 4, 5, 6, 7, 8, 9);
shuffle($arr);
echo join(' ', $arr) . "\n";
function fisher_yates_shuffle(&$a)
{
$size = count($a) - 1;
for($i = $size; $i >= 0; $i--)
{
if (($j = rand(0, $i)) != $i)
list($a[$i], $a[$j]) = array($a[$j], $a[$i]);
}
}
function naive_shuffle(&$a)
{
$size = count($a);
for($i = 0; $i < $size; $i++)
{
$j = rand(0, $size - 1);
list($a[$i], $a[$j]) = array($a[$j], $a[$i]);
}
}
$arr = array(1, 2, 3, 4, 5, 6, 7, 8, 9);
fisher_yates_shuffle($arr);
echo join(' ', $arr) . "\n";
naive_shuffle($arr);
echo join(' ', $arr) . "\n";
$age = array('Nat' => 24, 'Jules' => 25, 'Josh' => 17);
$age['Nat'] = 24;
$age['Jules'] = 25;
$age['Josh'] = 17;
$age = array_combine(array('Nat', 'Jules', 'Josh'), array(24, 25, 17));
$food_colour = array('Apple' => 'red', 'Banana' => 'yellow',
'Lemon' => 'yellow', 'Carrot' => 'orange');
$food_colour['Apple'] = 'red'; $food_colour['Banana'] = 'yellow';
$food_colour['Lemon'] = 'yellow'; $food_colour['Carrot'] = 'orange';
$food_colour = array_combine(array('Apple', 'Banana', 'Lemon', 'Carrot'),
array('red', 'yellow', 'yellow', 'orange'));
$hash[$key] = $value;
$food_colour = array('Apple' => 'red', 'Banana' => 'yellow',
'Lemon' => 'yellow', 'Carrot' => 'orange');
$food_colour['Raspberry'] = 'pink';
echo "Known foods:\n";
foreach($food_colour as $food => $colour) echo "{$food}\n";
if (isset($hash[$key]))
; else
;
if (array_key_exists($key, $hash))
; else
;
$food_colour = array('Apple' => 'red', 'Banana' => 'yellow',
'Lemon' => 'yellow', 'Carrot' => 'orange');
foreach(array('Banana', 'Martini') as $name)
{
if (isset($food_colour[$name]))
echo "{$name} is a food.\n";
else
echo "{$name} is a drink.\n";
}
$age = array('Toddler' => 3, 'Unborn' => 0, 'Phantasm' => NULL);
foreach(array('Toddler', 'Unborn', 'Phantasm', 'Relic') as $thing)
{
echo "{$thing}:";
if (array_key_exists($thing, $age)) echo ' exists';
if (isset($age[$thing])) echo ' non-NULL';
if ($age[$thing]) echo ' TRUE';
echo "\n";
}
unset($hash[$key]);
unset($hash[$key1], $hash[$key2], $hash[$key3]);
unset($hash);
function print_foods()
{
global $food_colour;
$foods = array_keys($food_colour);
echo 'Foods:';
foreach($foods as $food) echo " {$food}";
echo "\nValues:\n";
foreach($foods as $food)
{
$colour = $food_colour[$food];
if (isset($colour))
echo " {$colour}\n";
else
echo " nullified or removed\n";
}
}
$food_colour = array('Apple' => 'red', 'Banana' => 'yellow',
'Lemon' => 'yellow', 'Carrot' => 'orange');
echo "Initially:\n"; print_foods();
$food_colour['Banana'] = NULL;
echo "\nWith 'Banana' nullified\n";
print_foods();
unset($food_colour['Banana']);
echo "\nWith 'Banana' removed\n";
print_foods();
unset($food_colour);
foreach($hash as $key => $value)
{
; }
foreach(array_keys($hash) as $key)
{
; }
foreach($hash as $value)
{
; }
$food_colour = array('Apple' => 'red', 'Banana' => 'yellow',
'Lemon' => 'yellow', 'Carrot' => 'orange');
foreach($food_colour as $food => $colour)
{
echo "{$food} is {$colour}\n";
}
foreach(array_keys($food_colour) as $food)
{
echo "{$food} is {$food_colour[$food]}\n";
}
$line = fgets(STDIN);
while (!feof(STDIN))
{
if (preg_match('/^From: (.*)/', $line, $matches))
{
if (isset($from[$matches[1]]))
$from[$matches[1]] += 1;
else
$from[$matches[1]] = 1;
}
$line = fgets(STDIN);
}
if (isset($from))
{
echo "Senders:\n";
foreach($from as $sender => $count) echo "{$sender} : {$count}\n";
}
else
{
echo "No valid data entered\n";
}
print_r($hash);
foreach($hash as $key => $value)
{
echo "{$key} => $value\n";
}
ksort($hash);
$keys = array_keys($hash); sort($keys);
foreach($keys as $key)
{
echo "{$key} => {$hash[$key]}\n";
}
asort($hash);
where$values = array_values($hash); sort($values);
foreach($values as $value)
{
echo $value . ' <= ' . array_search($value, $hash) . "\n";
}
function array_push_associative(&$arr)
{
foreach (func_get_args() as $arg)
{
if (is_array($arg))
foreach ($arg as $key => $value) { $arr[$key] = $value; $ret++; }
else
$arr[$arg] = '';
}
return $ret;
}
$food_colour = array();
array_push_associative($food_colour, array('Banana' => 'Yellow'));
array_push_associative($food_colour, array('Apple' => 'Green'));
array_push_associative($food_colour, array('Lemon' => 'Yellow'));
print_r($food_colour);
echo "\nIn insertion order:\n";
foreach($food_colour as $food => $colour) echo " {$food} => {$colour}\n";
$foods = array_keys($food_colour);
echo "\nStill in insertion order:\n";
foreach($foods as $food) echo " {$food} => {$food_colour[$food]}\n";
foreach(array_slice(preg_split('/\n/', `who`), 0, -1) as $entry)
{
list($user, $tty) = preg_split('/\s/', $entry);
$ttys[$user][] = $tty;
}
ksort($ttys);
foreach($ttys as $user => $all_ttys)
{
echo "{$user}: " . join(' ', $all_ttys) . "\n";
}
foreach($ttys as $user => $all_ttys)
{
echo "{$user}: " . join(' ', $all_ttys) . "\n";
foreach($all_ttys as $tty)
{
$stat = stat('/dev/$tty');
$pwent = posix_getpwuid($stat['uid']);
$user = isset($pwent['name']) ? $pwent['name'] : 'Not available';
echo "{$tty} owned by: {$user}\n";
}
}
$reverse = array_flip($hash);
$surname = array('Babe' => 'Ruth', 'Mickey' => 'Mantle');
$first_name = array_flip($surname);
echo "{$first_name['Mantle']}\n";
$argc == 2 || die("usage: {$argv[0]} food|colour\n");
$given = $argv[1];
$colour = array('Apple' => 'red', 'Banana' => 'yellow',
'Lemon' => 'yellow', 'Carrot' => 'orange');
$food = array_flip($colour);
if (isset($colour[$given]))
echo "{$given} is a food with colour: {$colour[$given]}\n";
if (isset($food[$given]))
echo "{$food[$given]} is a food with colour: {$given}\n";
$food_colour = array('Apple' => 'red', 'Banana' => 'yellow',
'Lemon' => 'yellow', 'Carrot' => 'orange');
foreach($food_colour as $food => $colour)
{
$foods_with_colour[$colour][] = $food;
}
$colour = 'yellow';
echo "foods with colour {$colour} were: " . join(' ', $foods_with_colour[$colour]) . "\n";
ksort($hash);
krsort($hash);
function comparator($left, $right)
{
return $left > $right;
}
uksort($hash, 'comparator');
$food_colour = array('Apple' => 'red', 'Banana' => 'yellow',
'Lemon' => 'yellow', 'Carrot' => 'orange');
ksort($food_colour);
foreach($food_colour as $food => $colour)
{
echo "{$food} is {$colour}\n";
}
uksort($food_colour, create_function('$left, $right', 'return $left > $right;'));
foreach($food_colour as $food => $colour)
{
echo "{$food} is {$colour}\n";
}
$merged = array_merge($a, $b, $c);
$hash = array_combine($keys, $values);
foreach(array($h1, $h2, $h3) as $hash)
{
foreach($hash as $key => $value)
{
$merged[$key] = $value;
}
}
$food_colour = array('Apple' => 'red', 'Banana' => 'yellow',
'Lemon' => 'yellow', 'Carrot' => 'orange');
$drink_colour = array('Galliano' => 'yellow', 'Mai Tai' => 'blue');
$ingested_colour = array_merge($food_colour, $drink_colour);
$substance_colour = array();
foreach(array($food_colour, $drink_colour) as $hash)
{
foreach($hash as $substance => $colour)
{
if (array_key_exists($substance, $substance_colour))
{
echo "Warning {$substance_colour[$substance]} seen twice. Using first definition.\n";
continue;
}
$substance_colour[$substance] = $colour;
}
}
$common = array_intersect_key($h1, $h2);
$this_not_that = array_diff_key($h1, $h2);
$food_colour = array('Apple' => 'red', 'Banana' => 'yellow',
'Lemon' => 'yellow', 'Carrot' => 'orange');
$citrus_colour = array('Lemon' => 'yellow', 'Orange' => 'orange', 'Lime' => 'green');
$non_citrus = array_diff_key($food_colour, $citrus_colour);
$filenames = array('/etc/termcap', '/vmlinux', '/bin/cat');
foreach($filenames as $filename)
{
if (!($fh = fopen($filename, 'r'))) continue;
$name[$filename] = $fh;
}
foreach(array_values($name) as $fh)
{
fclose($fh);
}
$hash = array();
$hash = array('Apple' => 'red', 'Lemon' => 'yellow', 'Carrot' => 'orange');
foreach($array as $element) $count[$element] += 1;
$father = array('Cain' => 'Adam', 'Abel' => 'Adam', 'Seth' => 'Adam', 'Enoch' => 'Cain',
'Irad' => 'Enoch', 'Mehujael' => 'Irad', 'Methusael'=> 'Mehujael',
'Lamech' => 'Methusael', 'Jabal' => 'Lamech', 'Jubal' => 'Lamech',
'Tubalcain' => 'Lamech', 'Enos' => 'Seth');
$name = trim(fgets(STDIN));
while (!feof(STDIN))
{
while (TRUE)
{
echo "$name\n";
if (!isset($father[$name])) break;
$name = $father[$name];
}
echo "\n";
$name = trim(fgets(STDIN));
}
define(SEP, ' ');
foreach($father as $child => $parent)
{
if (!$children[$parent])
$children[$parent] = $child;
else
$children[$parent] .= SEP . $child;
}
$name = trim(fgets(STDIN));
while (!feof(STDIN))
{
echo $name . ' begat ';
if (!$children[$name])
echo "Nothing\n"
else
echo str_replace(SEP, ', ', $children[$name]) . "\n";
$name = trim(fgets(STDIN));
}
define(SEP, ' ');
$files = array('/tmp/a', '/tmp/b', '/tmp/c');
foreach($files as $file)
{
if (!is_file($file)) { echo "Skipping {$file}\n"; continue; }
if (!($fh = fopen($file, 'r'))) { echo "Skipping {$file}\n"; continue; }
$line = fgets($fh);
while (!feof($fh))
{
if (preg_match('/^\s*#\s*include\s*<([^>]+)>/', $line, $matches))
{
if (isset($includes[$matches[1]]))
$includes[$matches[1]] .= SEP . $file;
else
$includes[$matches[1]] = $file;
}
$line = fgets($fh);
}
fclose($fh);
}
print_r($includes);
$entry = stat('/bin/vi');
$entry = stat('/usr/bin');
$entry = stat($argv[1]);
$entry = stat('/bin/vi');
$ctime = $entry['ctime'];
$size = $entry['size'];
function containsText($file)
{
$status = FALSE;
if (($fp = fopen($file, 'r')))
{
while (FALSE !== ($char = fgetc($fp)))
{
if ($char == "\n") { $status = TRUE; break; }
}
fclose($fp);
}
return $status;
}
function isTextFile($file)
{
$finfo = finfo_open(FILEINFO_NONE);
$status = (finfo_file($finfo, $file) == 'ASCII text');
finfo_close($finfo);
return $status;
}
function isTextFile($file)
{
return exec(trim('file -bN ' . escapeshellarg($file))) == 'ASCII text';
}
containsText($argv[1]) || die("File {$argv[1]} doesn't have any text in it\n");
isTextFile($argv[1]) || die("File {$argv[1]} doesn't have any text in it\n");
$dirname = '/usr/bin/';
($dirhdl = opendir($dirname)) || die("Couldn't open {$dirname}\n");
while (($file = readdir($dirhdl)) !== FALSE)
{
printf("Inside %s is something called: %s\n", $dirname, $file);
}
closedir($dirhdl);
$filename = 'example.txt';
$fs = stat($filename);
$readtime = $fs['atime'];
$writetime = $fs['mtime'];
touch($filename, $writetime, $readtime);
$filename = 'example.txt';
$fs = stat($filename);
$atime = $fs['atime'];
$mtime = $fs['mtime'];
define('SECONDS_PER_DAY', 60 * 60 * 24);
$atime -= 7 * SECONDS_PER_DAY;
$mtime -= 7 * SECONDS_PER_DAY;
$atime = strtotime('-7 days', $atime);
$mtime = strtotime('-7 days', $mtime);
touch($filename, $mtime, $atime);
clearstatcache();
$argc == 2 || die("usage: {$argv[0]} filename\n");
$filename = $argv[1];
$fs = stat($filename);
$atime = $fs['atime'];
$mtime = $fs['mtime'];
system(trim(getenv('EDITOR') . ' vi ' . escapeshellarg($filename)), $retcode);
touch($filename, $mtime, $atime) || die("Error updating timestamp on file, {$filename}!\n");
$filename = '...';
@unlink($filename) || die("Can't delete, {$filename}!\n");
$files = glob('...');
$problem = FALSE;
foreach($files as $filename) { @unlink($filename) || $problem = TRUE; }
if ($problem)
{
fwrite(STDERR, 'Could not delete all of:');
foreach($files as $filename) { fwrite(STDERR, ' ' . $filename); }
fwrite(STDERR, "\n"); exit(1);
}
function rmAll($files)
{
$count = 0;
foreach($files as $filename) { @unlink($filename) && $count++; };
return $count;
}
$files = glob('...');
$toBeDeleted = sizeof($files);
$count = rmAll($files);
($count == $toBeDeleted) || die("Could only delete {$count} of {$toBeDeleted} files\n");
$oldfile = '/tmp/old'; $newfile = '/tmp/new';
copy($oldfile, $newfile) || die("Error copying file\n");
of$oldfile = '/tmp/old'; $newfile = '/tmp/new';
if (is_file($oldfile))
file_put_contents($newfile, file_get_contents($oldfile));
else
die("Problem copying file {$oldfile} to file {$newfile}\n");
$oldfile = '/tmp/old'; $newfile = '/tmp/new';
fwrite(($nh = fopen($newfile, 'wb')), fread(($oh = fopen($oldfile, 'rb')), filesize($oldfile)));
fclose($oh);
fclose($nh);
$oldfile = '/tmp/old'; $newfile = '/tmp/new';
($oh = fopen($oldfile, 'rb')) || die("Problem opening input file {$oldfile}\n");
($nh = fopen($newfile, 'wb')) || die("Problem opening output file {$newfile}\n");
if (($filesize = filesize($oldfile)) > 0)
{
fwrite($nh, fread($oh, $filesize)) || die("Problem reading / writing file data\n");
}
fclose($oh);
fclose($nh);
$oldfile = '/tmp/old'; $newfile = '/tmp/new';
is_file($newfile) && unlink($newfile);
exec(trim('cp --force ' . escapeshellarg($oldfile) . ' ' . escapeshellarg($newfile)));
is_file($newfile) || die("Problem copying file {$oldfile} to file {$newfile}\n");
function makeDevInodePair($filename)
{
if (!($fs = @stat($filename))) return FALSE;
return strval($fs['dev'] . $fs['ino']);
}
function do_my_thing($filename)
{
global $seen;
$devino = makeDevInodePair($filename);
if (!isset($seen[$devino]))
{
$seen[$devino] = 1;
}
else
{
$seen[$devino] += 1;
}
}
$seen = array();
do_my_thing('/tmp/old');
do_my_thing('/tmp/old');
do_my_thing('/tmp/old');
do_my_thing('/tmp/new');
foreach($seen as $devino => $count)
{
echo "{$devino} -> {$count}\n";
}
function array_update($arr, $lambda, $updarr)
{
foreach($arr as $key) $lambda($updarr, $key);
return $updarr;
}
function do_my_thing(&$seen, $filename)
{
if (!array_key_exists(($devino = makeDevInodePair($filename)), $seen))
{
$seen[$devino] = 1;
}
else
{
$seen[$devino] += 1;
}
}
$files = array('/tmp/old', '/tmp/old', '/tmp/old', '/tmp/new');
$seen = array();
array_update($files, 'do_my_thing', &$seen);
$seen = array_update($files, 'do_my_thing', array());
array_update($files,
create_function('$seen, $filename', '... code not shown ...'),
&$seen);
foreach($seen as $devino => $count)
{
echo "{$devino} -> {$count}\n";
}
$files = glob('/tmp/*');
define(SEP, ';');
$seen = array();
foreach($files as $filename)
{
if (!array_key_exists(($devino = makeDevInodePair($filename)), $seen))
$seen[$devino] = $filename;
else
$seen[$devino] = $seen[$devino] . SEP . $filename;
}
$devino = array_keys($seen);
sort($devino);
foreach($devino as $key)
{
echo $key . ':';
foreach(split(SEP, $seen[$key]) as $filename) echo ' ' . $filename;
echo "\n";
}
$dirname = '/usr/bin/';
($dirhdl = opendir($dirname)) || die("Couldn't open {$dirname}\n");
while (($file = readdir($dirhdl)) !== FALSE)
{
; }
closedir($dirhdl);
$dirname = '/usr/bin/';
foreach(scandir($dirname) as $file)
{
; }
$newlist = array_update(array_reverse(scandir($dirname)),
create_function('$filelist, $file', ' ; '),
array());
foreach(glob($dirname . '*') as $path)
{
; }
$dirname = '/usr/bin/';
echo "Text files in {$dirname}:\n";
foreach(scandir($dirname) as $file)
{
$path = $dirname . $file;
if (is_file($path) && isTextFile($path)) echo $path . "\n";
}
function plain_files($dirname)
{
($dirlist = glob($dirname . '*')) || die("Couldn't glob {$dirname}\n");
return array_filter($dirlist, 'is_file');
}
foreach(plain_files('/tmp/') as $path)
{
echo $path . "\n";
}
$dirname = '/tmp/';
$pathlist = glob($dirname . '*.c');
$filelist = array_filter(scandir($dirname),
create_function('$file', 'return fnmatch("*.c", $file);'));
$dirname = '/tmp/';
-insensitive$filelist = array_filter(scandir($dirname),
create_function('$file', 'return eregi("\.[ch]$", $file);'));
$dirname = '/tmp/';
$dirs = array_filter(glob($dirname . '*', GLOB_ONLYDIR),
create_function('$path', 'return ereg("^[0-9]+$", basename($path));'));
class Accumulator
{
public $value;
public function __construct($start_value) { $this->value = $start_value; }
}
function process_directory_($op, $func_args)
{
if (is_dir($func_args[0]))
{
$current = $func_args[0];
foreach(scandir($current) as $entry)
{
if ($entry == '.' || $entry == '..') continue;
$func_args[0] = $current . '/' . $entry;
process_directory_($op, $func_args);
}
}
else
{
call_user_func_array($op, $func_args);
}
}
function process_directory($op, $dir)
{
if (!is_dir($dir)) return FALSE;
$func_args = array_slice(func_get_args(), 1);
process_directory_($op, $func_args);
return TRUE;
}
$dirlist = array('/tmp/d1', '/tmp/d2', '/tmp/d3');
foreach($dirlist as $dir)
{
;
}
$dirlist = array('/tmp/d1', '/tmp/d2', '/tmp/d3');
function pf($path)
{
printf("%s\n", $path);
}
foreach($dirlist as $dir)
{
if (!is_dir($dir)) { printf("%s does not exist\n", $dir); continue; }
$filelist = scandir($dir);
if (count($filelist) == 2) { printf("%s is empty\n", $dir); continue; }
foreach($filelist as $file)
{
if ($file == '.' || $file == '..') continue;
pf($dir . '/' . $file);
}
}
function accum_filesize($file, $accum)
{
is_file($file) && ($accum->value += filesize($file));
}
$argc == 2 || die("usage: {$argv[0]} dir\n");
$dir = $argv[1];
is_dir($dir) || die("{$dir} does not exist / not a directory\n");
$dirsize = new Accumulator(0);
process_directory('accum_filesize', $dir, $dirsize);
printf("%s contains %d bytes\n", $dir, $dirsize->value);
function biggest_file($file, $accum)
{
if (is_file($file))
{
$fs = filesize($file);
if ($accum->value[1] < $fs) { $accum->value[0] = $file; $accum->value[1] = $fs; }
}
}
$argc == 2 || die("usage: {$argv[0]} dir\n");
$dir = $argv[1];
is_dir($dir) || die("{$dir} does not exist / not a directory\n");
$biggest = new Accumulator(array('', 0));
process_directory('biggest_file', $dir, $biggest);
printf("Biggest file is %s containing %d bytes\n", $biggest->value[0], $biggest->value[1]);
function youngest_file($file, $accum)
{
if (is_file($file))
{
$fct = filectime($file);
if ($accum->value[1] > $fct) { $accum->value[0] = $file; $accum->value[1] = $fct; }
}
}
$argc == 2 || die("usage: {$argv[0]} dir\n");
$dir = $argv[1];
is_dir($dir) || die("{$dir} does not exist / not a directory\n");
$youngest = new Accumulator(array('', 2147483647));
process_directory('youngest_file', $dir, $youngest);
printf("Youngest file is %s dating %s\n", $youngest->value[0], date(DATE_ATOM, $youngest->value[1]));
function rmtree_($dir)
{
$dir = "$dir";
if ($dh = opendir($dir))
{
while (FALSE !== ($item = readdir($dh)))
{
if ($item != '.' && $item != '..')
{
$subdir = $dir . '/' . "$item";
if (is_dir($subdir)) rmtree_($subdir);
else @unlink($subdir);
}
}
closedir($dh); @rmdir($dir);
}
}
function rmtree($dir)
{
if (is_dir($dir))
{
(substr($dir, -1, 1) == '/') && ($dir = substr($dir, 0, -1));
rmtree_($dir); return !is_dir($dir);
}
return FALSE;
}
$argc == 2 || die("usage: rmtree dir\n");
rmtree($argv[1]) || die("Could not remove directory {$argv[1]}\n");
$filepairs = array('x.txt' => 'x2.txt', 'y.txt' => 'y.doc', 'zxc.txt' => 'cxz.txt');
foreach($filepairs as $oldfile => $newfile)
{
@rename($oldfile, $newfile) || fwrite(STDERR, sprintf("Could not rename %s to %s\n", $oldfile, $newfile));
}
$oldfile = '/tmp/old'; $newfile = '/tmp/new';
is_file($newfile) && unlink($newfile);
exec(trim('mv --force ' . escapeshellarg($oldfile) . ' ' . escapeshellarg($newfile)));
is_file($oldfile) || die("Problem renaming file {$oldfile} to file {$newfile}\n");
$argc > 2 || die("usage: rename from to [file ...]\n");
$from = $argv[1];
$to = $argv[2];
if (count(($argv = array_slice($argv, 3))) < 1)
while (!feof(STDIN)) $argv[] = substr(fgets(STDIN), 0, -1);
foreach($argv as $file)
{
$was = $file;
$file = ereg_replace($from, $to, $file);
if (strcmp($was, $file) != 0)
@rename($was, $file) || fwrite(STDERR, sprintf("Could not rename %s to %s\n", $was, $file));
}
$base = basename($path);
$dir = dirname($path);
$pathinfo = pathinfo($path);
$base = $pathinfo['basename'];
$dir = $pathinfo['dirname'];
$ext = $pathinfo['extension'];
$path = '/usr/lib/libc.a';
printf("dir is %s, file is %s\n", dirname($path), basename($path));
$path = '/usr/lib/libc.a';
$pathinfo = pathinfo($path);
printf("dir is %s, name is %s, extension is %s\n", $pathinfo['dirname'], $pathinfo['basename'], $pathinfo['extension']);
$path = 'Hard%20Drive:System%20Folder:README.txt';
$macp = array_combine(array('drive', 'folder', 'filename'), split("\:", str_replace('%20', ' ', $path)));
$macf = array_combine(array('name', 'extension'), split("\.", $macp['filename']));
printf("dir is %s, name is %s, extension is %s\n", ($macp['drive'] . ':' . $macp['folder']), $macf['name'], ('.' . $macf['extension']));
function file_extension($filename, $separator = '.')
{
return end(split(("\\" . $separator), $filename));
}
echo file_extension('readme.txt') . "\n";
$greeted = 0;
function howManyGreetings()
{
global $greeted;
return $greeted;
}
function hello()
{
global $greeted;
$greeted++;
echo "high there!, this procedure has been called {$greeted} times\n";
}
hello();
$greetings = howManyGreetings();
echo "bye there!, there have been {$greetings} greetings so far\n";
function hypotenuse($side1, $side2)
{
return sqrt(pow($side1, 2) + pow($side2, 2));
}
function hypotenuse()
{
$side1 = func_get_arg(0); $side2 = func_get_arg(1);
return sqrt(pow($side1, 2) + pow($side2, 2));
}
$diag = hypotenuse(3, 4);
$funcname = 'hypotenuse';
$diag = call_user_func($funcname, 3, 4);
$args = array(3, 4);
$diag = call_user_func_array($funcname, $args);
$nums = array(1.4, 3.5, 6.7);
function int_all($arr)
{
return array_map(create_function('$n', 'return (int) $n;'), $arr);
}
function trunc_em(&$n)
{
foreach ($n as &$value) $value = (int) $value;
}
$ints = int_all($nums);
trunc_em($nums);
function some_func()
{
$variable = 'something';
}
$name = $argv[1]; $age = $argv[2];
$c = fetch_time();
$condition = 0;
function run_check()
{
global $condition, $name, $age, $c;
$condition = 1;
}
function check_x($x)
{
$y = 'whatever';
run_check();
global $condition;
if ($condition)
{
; }
}
{
$myvariable = 7;
}
echo $myvariable . "\n";
{
$counter = 0;
function next_counter() { global $counter; $counter++; }
}
class BEGIN
{
private $myvariable;
function __construct()
{
$this->myvariable = 5;
}
function othersub()
{
echo $this->myvariable . "\n";
}
}
$b = new BEGIN();
$b->othersub();
class Counter
{
private $counter;
function __construct($counter_init)
{
$this->counter = $counter_init;
}
function next_counter() { $this->counter++; return $this->counter; }
function prev_counter() { $this->counter; return $this->counter; }
}
$counter = new Counter(42);
echo $counter->next_counter() . "\n";
echo $counter->next_counter() . "\n";
echo $counter->prev_counter() . "\n";
function whoami()
{
$name = 'whoami';
echo "I am: {$name}\n";
}
whoami();
function array_by_value($arr)
{
$arr[0] = 7;
echo $arr[0] . "\n";
}
function array_by_ref(&$arr)
{
$arr[0] = 7;
echo $arr[0] . "\n";
}
$arr = array(1, 2, 3);
echo $arr[0] . "\n"; array_by_value($arr); echo $arr[0] . "\n";
$arr = array(1, 2, 3);
echo $arr[0] . "\n"; array_by_ref($arr); echo $arr[0] . "\n";
function add_vecpair($x, $y)
{
$r = array();
$length = count($x);
for($i = 0; $i < $length; $i++) $r[$i] = $x[$i] + $y[$i];
return $r;
}
count($arr1) == count($arr2) || die("usage: add_vecpair ARR1 ARR2\n");
$arr3 = add_vecpair($arr1, $arr2);
$arr3 = add_vecpair(&$arr1, &$arr2);
function mysub()
{
return 5;
return array(5);
return '5';
}
mysub();
$ret = mysub();
if (is_numeric($ret))
{
; }
if (is_array($ret))
{
; }
if (is_string($ret))
{
; }
class KeyedValue
{
public $key, $value;
public function __construct($key, $value) { $this->key = $key; $this->value = $value; }
}
function the_func()
{
foreach (func_get_args() as $arg)
{
printf("Key: %10s|Value:%10s\n", $arg->key, $arg->value);
}
}
the_func(new KeyedValue('name', 'Bob'),
new KeyedValue('age', 36),
new KeyedValue('income', 51000));
function the_func($var_array)
{
extract($var_array);
if (isset($name)) printf("Name: %s\n", $name);
if (isset($age)) printf("Age: %s\n", $age);
if (isset($income)) printf("Income: %s\n", $income);
}
the_func(array('name' => 'Bob', 'age' => 36, 'income' => 51000));
class RaceTime
{
public $time, $dim;
public function __construct($time, $dim) { $this->time = $time; $this->dim = $dim; }
}
function the_func($var_array)
{
extract($var_array);
if (isset($start_time)) printf("start: %d - %s\n", $start_time->time, $start_time->dim);
if (isset($finish_time)) printf("finish: %d - %s\n", $finish_time->time, $finish_time->dim);
if (isset($incr_time)) printf("incr: %d - %s\n", $incr_time->time, $incr_time->dim);
}
the_func(array('start_time' => new RaceTime(20, 's'),
'finish_time' => new RaceTime(5, 'm'),
'incr_time' => new RaceTime(3, 'm')));
the_func(array('start_time' => new RaceTime(5, 'm'),
'finish_time' => new RaceTime(30, 'm')));
the_func(array('start_time' => new RaceTime(30, 'm')));
function func() { return array(3, 6, 9); }
list($a, $b, $c) = array(6, 7, 8);
list($a, $b, $c) = func();
unset($b);
list($a,,$c) = func();
list($dev, $ino,,,$uid) = array_slice(array_values(stat($filename)), 0, 13);
function some_func() { return array(array(1, 2, 3), array('a' => 1, 'b' => 2)); }
list($arr, $hash) = some_func();
function some_func(&$arr, &$hash) { return array($arr, $hash); }
$arrin = array(1, 2, 3); $hashin = array('a' => 1, 'b' => 2);
list($arr, $hash) = some_func($arrin, $hashin);
function a_func() { return FALSE; }
a_func() || die("Function failed\n");
if (!a_func()) die("Function failed\n");
function func_with_one_arg($arg1)
{
; }
function func_with_two_arg($arg1, $arg2)
{
; }
function func_with_three_arg($arg1, $arg2, $arg3)
{
; }
function func_with_no_arg()
{
; }
function func_with_no_arg_information()
{
; }
die("some message\n");
class MyException extends Exception
{
}
try
{
if ($some_problem_detected) throw new MyException('some message', $some_error_code);
}
catch (MyException $e)
{
; }
class FullMoonException extends Exception
{
}
try
{
if ($some_problem_detected) throw new FullMoonException('...', $full_moon_error_code);
}
catch (FullMoonException $e)
{
throw $e;
}
it
function expand() { echo "expand\n"; }
echo (function_exists('expand') ? 'yes' : 'no') . "\n";
$grow = 'expand';
expand();
$grow();
unset($grow);
function fred() { echo "fred\n"; }
$barney = 'fred';
$barney();
unset($barney);
fred();
$fred = create_function('', 'echo "fred\n";');
$barney = $fred;
$barney();
unset($barney);
$fred();
function red($text) { return "<FONT COLOR='red'>$text</FONT>"; }
echo red('careful here') . "\n";
$colour = 'red';
$$colour = create_function('$text', 'global $colour;
return "<FONT COLOR=\'$colour\'>$text</FONT>";');
echo $$colour('careful here') . "\n";
unset($$colour);
$colours = split(' ', 'red blue green yellow orange purple violet');
foreach ($colours as $colour)
{
$$colour = create_function('$text', 'global $colour;
return "<FONT COLOR=\'$colour\'>$text</FONT>";');
}
foreach ($colours as $colour) { echo $$colour("Careful with this $colour, James") . "\n"; }
foreach ($colours as $colour) { unset($$colour); }
function __autoload($classname)
{
if (!file_exists($classname))
{
die("File for class: {$classname} not found - aborting\n");
}
else
{
require_once $classname;
}
}
new UnknownClassObject();
$colours = array('red', 'blue', 'green', 'yellow', 'orange', 'purple', 'violet');
foreach ($colours as $colour)
{
$$colour = create_function('$text', 'global $colour;
return "<FONT COLOR=\'$colour\'>$text</FONT>";');
}
array_push($colours, 'chartreuse');
foreach ($colours as $colour)
{
if (!function_exists($$colour))
{
$$colour = create_function('$text', 'global $colour;
return "<FONT COLOR=\'$colour\'>$text</FONT>";');
}
echo $$colour("Careful with this $colour, James") . "\n";
}
foreach ($colours as $colour) unset($$colour);
function outer($arg)
{
$x = $arg + 35;
function inner() { return $x * 19; }
return $x + inner();
}
function outer($arg)
{
$x = $arg + 35;
function inner($x) { return $x * 19; }
return $x + inner($x);
}
function inner($x)
{
return $x * 19;
}
function outer($arg)
{
$x = $arg + 35;
return $x + inner($x);
}
$output_string = shell_exec('program args');
$output_string = `program args`;
$output_lines = array();
exec('program args', $output_lines);
$pid = pcntl_fork();
if ($pid == -1) {
die('cannot fork');
} elseif ($pid) {
pcntl_waitpid($pid, $status);
} else {
pcntl_exec($program, array($arg1, $arg2));
}
exec("vi $myfile", $output, $result_code);
exec('cmd1 args | cmd2 | cmd3 >outfile');
exec('cmd args <infile >outfile 2>errfile');
$pid = pcntl_fork();
if ($pid == -1) {
die('cannot fork');
} elseif ($pid) {
pcntl_waitpid($pid, $status);
if (pcntl_wifexited($status)) {
$status = pcntl_wexitstatus($status);
echo "program exited with status $status\n";
} elseif (pcntl_wifsignaled($status)) {
$signal = pcntl_wtermsig($status);
echo "program killed by signal $signal\n";
} elseif (pcntl_wifstopped($status)) {
$signal = pcntl_wstopsig($status);
echo "program stopped by signal $signal\n";
}
} else {
pcntl_exec($program, $args);
}
$pid = pcntl_fork();
if ($pid == -1) {
die('cannot fork');
} elseif ($pid) {
declare(ticks = 1);
function handle_sigint($signal) {
echo "Tsk tsk, no process interruptus\n";
}
pcntl_signal(SIGINT, 'handle_sigint');
while (!pcntl_waitpid($pid, $status, WNOHANG)) {}
} else {
pcntl_signal(SIGINT, SIG_IGN);
pcntl_exec('/bin/sleep', array('10'));
}
pcntl_exec('/bin/sh', array('-c', 'archive *.data'));
pcntl_exec('/path/to/archive', array('accounting.data'));
$readme = popen('program arguments', 'r');
while (!feof($readme)) {
$line = fgets($readme);
if ($line === false) break;
}
pclose($readme);
$writeme = popen('program arguments', 'w');
fwrite($writeme, 'data');
pclose($writeme);
$f = popen('sleep 1000000', 'r'); pclose($f);
$writeme = popen('program arguments', 'w');
fwrite($writeme, "hello\n"); pclose($writeme);
function ob_pager($output, $mode) {
static $pipe;
if ($mode & PHP_OUTPUT_HANDLER_START) {
$pager = getenv('PAGER');
if (!$pager) $pager = '/usr/bin/less'; $pipe = popen($pager, 'w');
}
fwrite($pipe, $output);
if ($mode & PHP_OUTPUT_HANDLER_END) {
pclose($pipe);
}
}
ob_start('ob_pager');
ob_end_flush();
class Head {
function Head($lines=20) {
$this->lines = $lines;
}
function filter($output, $mode) {
$result = array();
$newline = '';
if (strlen($output) > 0 && $output[strlen($output) - 1] == "\n") {
$newline = "\n";
$output = substr($output, 0, -1);
}
foreach (explode("\n", $output) as $i => $line) {
if ($this->lines > 0) {
$this->lines--;
$result[] = $line;
}
}
return $result ? implode("\n", $result) . $newline : '';
}
}
class Number {
function Number() {
$this->line_number = 0;
}
function filter($output, $mode) {
$result = array();
$newline = '';
if (strlen($output) > 0 && $output[strlen($output) - 1] == "\n") {
$newline = "\n";
$output = substr($output, 0, -1);
}
foreach (explode("\n", $output) as $i => $line) {
$this->line_number++;
$result[] = $this->line_number . ': ' . $line;
}
return implode("\n", $result) . $newline;
}
}
class Quote {
function Quote() {
}
function filter($output, $mode) {
$result = array();
$newline = '';
if (strlen($output) > 0 && $output[strlen($output) - 1] == "\n") {
$newline = "\n";
$output = substr($output, 0, -1);
}
foreach (explode("\n", $output) as $i => $line) {
$result[] = "> $line";
}
return implode("\n", $result) . $newline;
}
}
ob_start(array(new Head(100), 'filter'));
ob_start(array(new Number(), 'filter'));
ob_start(array(new Quote(), 'filter'));
while (!feof(STDIN)) {
$line = fgets(STDIN);
if ($line === false) break;
echo $line;
}
ob_end_flush();
ob_end_flush();
ob_end_flush();
$filenames = array_slice($argv, 1);
if (!$filenames) $filenames = array('php://stdin');
foreach ($filenames as $filename) {
$handle = @fopen($filename, 'r');
if ($handle) {
while (!feof($handle)) {
$line = fgets($handle);
if ($line === false) break;
}
fclose($handle);
} else {
die("can't open $filename\n");
}
}
$output = `cmd 2>&1`; $ph = popen('cmd 2>&1'); while (!feof($ph)) { $line = fgets($ph); } $output = `cmd 2>/dev/null`; $ph = popen('cmd 2>/dev/null'); while (!feof($ph)) { $line = fgets($ph); } $output = `cmd 2>&1 1>/dev/null`; $ph = popen('cmd 2>&1 1>/dev/null'); while (!feof($ph)) { $line = fgets($ph); } $output = `cmd 3>&1 1>&2 2>&3 3>&-`; $ph = popen('cmd 3>&1 1>&2 2>&3 3>&-|'); while (!feof($ph)) { $line = fgets($ph); } exec('program args 1>/tmp/program.stdout 2>/tmp/program.stderr');
$output = `cmd 3>&1 1>&2 2>&3 3>&-`;
$fd3 = $fd1;
$fd1 = $fd2;
$fd2 = $fd3;
$fd3 = null;
exec('prog args 1>tmpfile 2>&1');
exec('prog args 2>&1 1>tmpfile');
$fd1 = "tmpfile"; $fd2 = $fd1; $fd2 = $fd1; $fd1 = "tmpfile";
$proc = proc_open($program,
array(0 => array('pipe', 'r'),
1 => array('pipe', 'w')),
$pipes);
if (is_resource($proc)) {
fwrite($pipes[0], "here's your input\n");
fclose($pipes[0]);
echo stream_get_contents($pipes[1]);
fclose($pipes[1]);
$result_code = proc_close($proc);
echo "$result_code\n";
}
$all = array();
$outlines = array();
$errlines = array();
exec("( $cmd | sed -e 's/^/stdout: /' ) 2>&1", $all);
foreach ($all as $line) {
$pos = strpos($line, 'stdout: ');
if ($pos !== false && $pos == 0) {
$outlines[] = substr($line, 8);
} else {
$errlines[] = $line;
}
}
print("STDOUT:\n");
print_r($outlines);
print("\n");
print("STDERR:\n");
print_r($errlines);
print("\n");
$proc = proc_open($cmd,
array(0 => array('pipe', 'r'),
1 => array('pipe', 'w'),
2 => array('pipe', 'w')),
$pipes);
if (is_resource($proc)) {
fclose($pipes[0]);
$outlines = array();
while (!feof($pipes[1])) {
$line = fgets($pipes[1]);
if ($line === false) break;
$outlines[] = rtrim($line);
}
$errlines = array();
while (!feof($pipes[2])) {
$line = fgets($pipes[2]);
if ($line === false) break;
$errlines[] = rtrim($line);
}
fclose($pipes[1]);
fclose($pipes[2]);
proc_close($proc);
print("STDOUT:\n");
print_r($outlines);
print("\n");
print("STDERR:\n");
print_r($errlines);
print("\n");
}
$cmd = "grep vt33 /none/such - /etc/termcap";
$proc = proc_open($cmd,
array(0 => array('pipe', 'r'),
1 => array('pipe', 'w'),
2 => array('pipe', 'w')),
$pipes);
if (is_resource($proc)) {
fwrite($pipes[0], "This line has a vt33 lurking in it\n");
fclose($pipes[0]);
$readers = array($pipes[1], $pipes[2]);
while (stream_select($read=$readers,
$write=null,
$except=null,
0, 200000) > 0) {
foreach ($read as $stream) {
$line = fgets($stream);
if ($line !== false) {
if ($stream === $pipes[1]) {
print "STDOUT: $line";
} else {
print "STDERR: $line";
}
}
if (feof($stream)) {
$readers = array_diff($readers, array($stream));
}
}
}
fclose($pipes[1]);
fclose($pipes[2]);
proc_close($proc);
}
$sockets = array();
if (!socket_create_pair(AF_UNIX, SOCK_STREAM, 0, $sockets)) {
die(socket_strerror(socket_last_error()));
}
list($reader, $writer) = $sockets;
$pid = pcntl_fork();
if ($pid == -1) {
die('cannot fork');
} elseif ($pid) {
socket_close($reader);
$line = sprintf("Parent Pid %d is sending this\n", getmypid());
if (!socket_write($writer, $line, strlen($line))) {
socket_close($writer);
die(socket_strerror(socket_last_error()));
}
socket_close($writer);
pcntl_waitpid($pid, $status);
} else {
socket_close($writer);
$line = socket_read($reader, 1024, PHP_NORMAL_READ);
printf("Child Pid %d just read this: `%s'\n", getmypid(), rtrim($line));
socket_close($reader); exit(0);
}
$sockets = array();
if (!socket_create_pair(AF_UNIX, SOCK_STREAM, 0, $sockets)) {
die(socket_strerror(socket_last_error()));
}
list($reader, $writer) = $sockets;
$pid = pcntl_fork();
if ($pid == -1) {
die('cannot fork');
} elseif ($pid) {
socket_close($writer);
$line = socket_read($reader, 1024, PHP_NORMAL_READ);
printf("Parent Pid %d just read this: `%s'\n", getmypid(), rtrim($line));
socket_close($reader);
pcntl_waitpid($pid, $status);
} else {
socket_close($reader);
$line = sprintf("Child Pid %d is sending this\n", getmypid());
if (!socket_write($writer, $line, strlen($line))) {
socket_close($writer);
die(socket_strerror(socket_last_error()));
}
socket_close($writer); exit(0);
}
$sockets = array();
if (!socket_create_pair(AF_UNIX, SOCK_STREAM, 0, $sockets)) {
die(socket_strerror(socket_last_error()));
}
list($child, $parent) = $sockets;
$pid = pcntl_fork();
if ($pid == -1) {
die('cannot fork');
} elseif ($pid) {
socket_close($parent);
$line = sprintf("Parent Pid %d is sending this\n", getmypid());
if (!socket_write($child, $line, strlen($line))) {
socket_close($child);
die(socket_strerror(socket_last_error()));
}
$line = socket_read($child, 1024, PHP_NORMAL_READ);
printf("Parent Pid %d just read this: `%s'\n", getmypid(), rtrim($line));
socket_close($child);
pcntl_waitpid($pid, $status);
} else {
socket_close($child);
$line = socket_read($parent, 1024, PHP_NORMAL_READ);
printf("Child Pid %d just read this: `%s'\n", getmypid(), rtrim($line));
$line = sprintf("Child Pid %d is sending this\n", getmypid());
if (!socket_write($parent, $line, strlen($line))) {
socket_close($parent);
die(socket_strerror(socket_last_error()));
}
socket_close($parent);
exit(0);
}
$fifo = fopen('/path/to/named.pipe', 'r');
if ($fifo !== false) {
while (!feof($fifo)) {
$line = fgets($fifo);
if ($line === false) break;
echo "Got: $line";
}
fclose($fifo);
} else {
die('could not open fifo for read');
}
$fifo = fopen('/path/to/named.pipe', 'w');
if ($fifo !== false) {
fwrite($fifo, "Smoke this.\n");
fclose($fifo);
} else {
die('could not open fifo for write');
}
you
while (true) {
$home = getenv('HOME');
$fifo = fopen("$home/.plan", 'w');
if ($fifo === false) {
die("Couldn't open $home/.plan for writing.\n");
}
fwrite($fifo,
'The current time is '
. strftime('%a, %d %b %Y %H:%M:%S %z')
. "\n");
fclose($fifo);
sleep(1);
}
$fifo = null;
declare(ticks = 1);
function handle_alarm($signal) {
global $fifo;
if ($fifo) fclose($fifo); }
pcntl_signal(SIGALRM, 'handle_alarm');
while (true) {
pcntl_alarm(0); $fifo = fopen('/tmp/log', 'r');
if ($fifo === false) {
die("can't open /tmp/log");
}
pcntl_alarm(1);
$service = fgets($fifo);
if ($service === false) continue; $service = rtrim($service);
$message = fgets($fifo);
if ($message === false) continue; $message = rtrim($message);
pcntl_alarm(0);
if ($service == 'http') {
} elseif ($service == 'login') {
$log = fopen('/var/log/login', 'a');
if ($log !== false) {
fwrite($log,
strftime('%a, %d %b %Y %H:%M:%S %z')
. " $service $message\n");
fclose($log);
} else {
trigger_error("Couldn't log $service $message to /var/log/login\n",
E_USER_WARNING);
}
}
}
$SHM_KEY = ftok(__FILE__, chr(1));
$handle = sem_get($SHM_KEY);
$buffer = shm_attach($handle, 1024);
for ($i = 0; $i < 10; $i++) {
$child = pcntl_fork();
if ($child == -1) {
die('cannot fork');
} elseif ($child) {
$kids[] = $child; we } else {
squabble();
exit();
}
}
while (true) {
print 'Buffer is ' . shm_get_var($buffer, 1) . "\n";
sleep(1);
}
die('Not reached');
function squabble() {
global $handle;
global $buffer;
$i = 0;
$pid = getmypid();
while (true) {
if (preg_match("/^$pid\\b/", shm_get_var($buffer, 1))) continue;
sem_acquire($handle);
$i++;
shm_put_var($buffer, 1, "$pid $i");
sem_release($handle);
}
}
% php -r 'print_r(get_defined_constants());' | grep '\[SIG' | grep -v _
[SIGHUP] => 1
[SIGINT] => 2
[SIGQUIT] => 3
[SIGILL] => 4
[SIGTRAP] => 5
[SIGABRT] => 6
[SIGIOT] => 6
[SIGBUS] => 7
[SIGFPE] => 8
[SIGKILL] => 9
[SIGUSR1] => 10
[SIGSEGV] => 11
[SIGUSR2] => 12
[SIGPIPE] => 13
[SIGALRM] => 14
[SIGTERM] => 15
[SIGSTKFLT] => 16
[SIGCLD] => 17
[SIGCHLD] => 17
[SIGCONT] => 18
[SIGSTOP] => 19
[SIGTSTP] => 20
[SIGTTIN] => 21
[SIGTTOU] => 22
[SIGURG] => 23
[SIGXCPU] => 24
[SIGXFSZ] => 25
[SIGVTALRM] => 26
[SIGPROF] => 27
[SIGWINCH] => 28
[SIGPOLL] => 29
[SIGIO] => 29
[SIGPWR] => 30
[SIGSYS] => 31
[SIGBABY] => 31
% php -r 'print_r(get_defined_constants());' | grep '\[SIG' | grep _
[SIG_IGN] => 1
[SIG_DFL] => 0
[SIG_ERR] => -1
posix_kill($pid, 9);
posix_kill($pgrp, -1);
posix_kill(getmypid(), SIGUSR1);
foreach ($pids as $pid) posix_kill($pid, SIGHUP);
if (posix_kill($minion, 0)) {
echo "$minion is alive!\n";
} else {
echo "$minion is deceased.\n";
}
pcntl_signal(SIGQUIT, 'got_sig_quit');
pcntl_signal(SIGPIPE, 'got_sig_pipe');
function got_sig_int($signal) { global $ouch; $ouch++; }
pcntl_signal(SIGINT, 'got_sig_int');
pcntl_signal(SIGINT, SIG_IGN);
pcntl_signal(SIGSTOP, SIG_DFL);
function ding($signal) {
fwrite(STDERR, "\x07Enter your name!\n");
}
function get_name() {
declare(ticks = 1);
pcntl_signal(SIGINT, 'ding');
echo "Kindly Stranger, please enter your name: ";
while (!@stream_select($read=array(STDIN),
$write=null,
$except=null,
1)) {
}
$name = fgets(STDIN);
pcntl_signal(SIGINT, SIG_DFL);
return $name;
}
function got_int($signal) {
pcntl_signal(SIGINT, 'got_int'); }
pcntl_signal(SIGINT, 'got_int');
declare(ticks = 1);
$interrupted = false;
function got_int($signal) {
global $interrupted;
$interrupted = true;
pcntl_signal(SIGINT, 'got_int', false); }
pcntl_signal(SIGINT, 'got_int', false);
if ($interrupted) {
}
pcntl_signal(SIGINT, SIG_IGN);
declare(ticks = 1);
function tsktsk($signal) {
fwrite(STDERR, "\x07The long habit of living indisposeth us for dying.");
pcntl_signal(SIGINT, 'tsktsk');
}
pcntl_signal(SIGINT, 'tsktsk');
pcntl_signal(SIGCHLD, SIG_IGN);
declare(ticks = 1);
function reaper($signal) {
$pid = pcntl_waitpid(-1, $status, WNOHANG);
if ($pid > 0) {
reaper($signal);
}
pcntl_signal(SIGCHLD, 'reaper');
}
pcntl_signal(SIGCHLD, 'reaper');
declare(ticks = 1);
function reaper($signal) {
$pid = pcntl_waitpid(-1, $status, WNOHANG);
if ($pid == -1) {
} else {
if (pcntl_wifexited($signal)) {
echo "Process $pid exited.\n";
} else {
echo "False alarm on $pid\n";
}
reaper($signal);
}
pcntl_signal(SIGCHLD, 'reaper');
}
pcntl_signal(SIGCHLD, 'reaper');
declare(ticks = 1);
$aborted = false;
function handle_alarm($signal) {
global $aborted;
$aborted = true;
}
pcntl_signal(SIGALRM, 'handle_alarm');
pcntl_alarm(3600);
pcntl_alarm(0);
if ($aborted) {
}