Solved Problems

Output a string to the console

Write the string "Hello World!" to STDOUT
php
echo 'Hello World!';
/****
* For some (security)reason I couldn't
* submit this without adding a space to
* the functionname. Please remove it :)
****/

// The correct way in command line-mode. :)
f write(STDOUT, "Hello World!\n");

Retrieve a string containing ampersands from the variables in a url

My PHP script first does a query to obtain customer info for a form. The form has first name and last name fields among others. The customer has put entries such as "Ron & Jean" in the first name field in the database. Then the edit form script is called with variables such as

"http://myserver.com/custinfo/edit.php?mode=view&fname=Ron & Jean&lname=Smith".

The script variable for first name $_REQUEST['firstname'] never gets beyond the "Ron" value because of the ampersand in the data.

I have tried various functions like urldecode but all to no avail. I even tried encoding the url before the view screen is painted so that the url looks like "http://myserver/custinfo/edit.php?mode=view&fname="Ronxxnbsp;xxamp;xxnbsp;Jean"&lname=SMITH". (sorry I had to add the xx to replace the ampersand or it didn't display meaningful url contents the browser sees.)

Of course this fails for the same reasons. What is a better approach?
php
/************************
* This is definitely not what this site is about
* This is not a site where you can get help with various problems
* It's a site where you can say:
* "How do you do the following in your language"
*
*************
*
* Anyway...
* I would use urlencode like you have tried
* (or to be on the safe side: rawurlencode() )
************************/

$parameter = "Bart & Lisa";
echo "<a href='".basename(__FILE__)."?fname=".$parameter."'>?fname=".$parameter."</a><br />\n";
echo "<a href='".basename(__FILE__)."?fname=".rawurlencode($parameter)."'>?fname=".rawurlencode($parameter)."</a><br />\n";

echo "<pre>", print_r($_REQUEST, true), "</pre>";

/***************
* Try to save this as a file and run the script
************
* If you hover the mouse over the link, they will look exactly the same
* but if you click them, they will output differently
***************/


// Cheers, "Josso"

echo("The given input URL is mal-formed; it should be URL-encoded. Use urldecode() on each argument to decode it.");

$url = parse_url("http://myserver.com/custinfo/edit.php?mode=view&fname=Ron & Jean&lname=Smith");
$query = $url['query'];
$query = preg_replace("/&(?=[^=]*&)/", "%26", $query);
parse_str($query, $querystring);
var_dump($querystring);

the result is >> array(3) {
["mode"]=>
string(4) "view"
["fname"]=>
string(10) "Ron & Jean"
["lname"]=>
string(5) "Smith"
}

string-wrap

Wrap the string "The quick brown fox jumps over the lazy dog. " repeated ten times to a max width of 78 chars, starting each line with "> "

Expected output:
> The quick brown fox jumps over the lazy dog. The quick brown fox jumps over t
> he lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox
> jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The qui
> ck brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy
> dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps o
> ver the lazy dog. The quick brown fox jumps over the lazy dog.
php
foreach(str_split(str_repeat("The quick brown fox jumps over the lazy dog. ", 10), 77) as $line)
printf("> %s\n", trim($line));

Define a string containing special characters

Define the literal string "\#{'}${"}/"
php
$special = "\\#{'}\${\"}/";
$special = '\#{\'}${"}/';

Define a multiline string

Define the string:
"This
Is
A
Multiline
String"
php
$multiline = <<<ML
This
Is
A
Multiline
String
ML;
$multiline = "This
Is
A
Multiline
String";
$multiline = "This\nIs\nA\nMultiline\nString";

Define a string containing variables and expressions

Given variables a=3 and b=4 output "3+4=7"
php
echo "$a+$b=".($a+$b);
printf("%d+%d=%d\n", $a, $b, $a + $b);

Reverse the characters in a string

Given the string "reverse me", produce the string "em esrever"
php
$reversed = strrev("reverse me");

Reverse the words in a string

Given the string "This is a end, my only friend!", produce the string "friend! only my end, the is This"
php
$reversed_words = implode(" ", array_reverse(explode(" ", "This is the end, my only friend!")));

Text wrapping

Wrap the string "The quick brown fox jumps over the lazy dog. " repeated ten times to a max width of 78 chars, starting each line with "> ", yielding this result:

> The quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog.
php
$s = str_repeat("The quick brown fox jumps over the lazy dog. ", 10);
$s = wordwrap($s, 76, "WRAP");
$s = explode("WRAP", $s);
foreach ($s as $part) {
$res .= "> " . $part . "\n";
}
echo $res;
echo '> '.wordwrap(str_repeat('The quick brown fox jumps over the lazy dog. ', 10), 70,"\n> ")."\n";

Remove leading and trailing whitespace from a string

Given the string "  hello    " return the string "hello".
php
$hello_trimmed = trim(" hello ");

Simple substitution cipher

Take a string and return the ROT13 and ROT47 (Check Wikipedia) version of the string.
For example:
String is: Hello World #123
ROT13 returns: Uryyb Jbeyq #123
ROT47 returns: w6==@ (@C=5 R`ab
php
function rot13($str) {
return strtr($str,
"NOPQRSTUVWXYZnopqrstuvwxyzABCDEFGHIJKLMabcdefghijklm",
"ABCDEFGHIJKLMabcdefghijklmNOPQRSTUVWXYZnopqrstuvwxyz");
}

function str_rot47($str) {
return strtr($str,
'!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~',
'PQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNO');
}

echo str_rot13("Hello World #123"); // builtin version
echo str_rot47("Hello World #123"); // homemade version
echo rot13("Hello World #123"); // homemade version

Make a string uppercase

Transform "Space Monkey" into "SPACE MONKEY"
php
echo strtoupper("Space Monkey");

Make a string lowercase

Transform "Caps ARE overRated" into "caps are overrated"
php
echo strtolower("Caps ARE overRated");

Capitalise the first letter of each word

Transform "man OF stEEL" into "Man Of Steel"
php
echo ucwords(strtolower("man OF stEEL"));

Find the distance between two points

php
$distance = sqrt( pow(($x2 - $x1), 2) + pow(($y2 - $y1),2) );
class Point2D {
var $x;
var $y;
function __construct($x, $y) {
$this->x = $x;
$this->y = $y;
}
}
$a = new Point2D($x1,$y1);
$b = new Point2D($x2,$y2);
$distance = sqrt( pow(($b->x - $a->x), 2) + pow(($b->y - $a->y),2) );

Zero pad a number

Given the number 42, pad it to 8 characters like 00000042
php
echo str_pad(42, 8, 0, STR_PAD_LEFT);
printf("%08d", 42);

Right Space pad a number

Given the number 1024 right pad it to 6 characters "1024  "
php
echo str_pad(1024, 6, " ");
printf("%s ", 1024);

Format a decimal number

Format the number 7/8 as a decimal with 2 places: 0.88
php
printf("%.2g", 7/8);
echo round(7/8, 2);

Left Space pad a number

Given the number 73 left pad it to 10 characters "        73"
php
echo str_pad(73, 10, " ", STR_PAD_LEFT);
printf("%10d", 73);

Generate a random integer in a given range

Produce a random integer between 100 and 200 inclusive
php
$r = mt_rand(100, 200);

Generate a repeatable random number sequence

Initialise a random number generator with a seed and generate five decimal values. Reset the seed and produce the same values.
php
mt_srand(9876);
$r1 = array();
foreach(range(1,5) as $i) {
$r1[$i] = mt_rand(1,100);
}
mt_srand(9876);
$r2 = array();
foreach(range(1,5) as $i) {
$r2[$i] = mt_rand(1,100);
}

Check if a string matches a regular expression

Display "ok" if "Hello" matches /[A-Z][a-z]+/
php
if(ereg('[A-Za-z]+', 'Hello')) {
echo "ok";
}
if(preg_match('/[A-Za-z]+/', 'Hello')>0) {
echo "ok";
}

Check if a string matches with groups

Display "two" if "one two three" matches /one (.*) three/
php
preg_match('/one (.*) three/', 'one two three', $matches);
echo $matches[1];
ereg('one (.*) three', 'one two three', $regs);
echo $regs[1];

Check if a string contains a match to a regular expression

Display "ok" if "abc 123 @#$" matches /\d+/
php
if (preg_match("/\d+/", "abc 123 @#$"))
echo "ok";

Loop through a string matching a regex and performing an action for each match

Create a list [fish1,cow3,boat4] when matching "(fish):1 sausage (cow):3 tree (boat):4" with regex /\((\w+)\):(\d+)/
php
preg_match_all("/\((\w+)\):(\d+)/", "(fish):1 sausage (cow):3 tree (boat):4", $matches);
for ($i=0, $c=count($matches[0]); $i < $c; $i++) {
$list[] = $matches[1][$i].$matches[2][$i];
}

Replace the first regex match in a string with a static string

Transform "Red Green Blue" into "R*d Green Blue" by replacing /e/ with "*"
php
echo preg_replace('/e/', '*', "Red Green Blue", 1);

Replace all regex matches in a string with a static string

Transform "She sells sea shells" into "She X X shells" by replacing /se\w+/ with "X"
php
echo preg_replace('/se\w+/', 'X', 'She sells sea shells');

Replace all regex matches in a string with a dynamic string

Transform "The {Quick} Brown {Fox}" into "The kciuQ Brown xoF" by reversing words in braces using the regex /\{(\w+)\}/.
php
// We have to use the e-modifier
preg_replace("/\{(\w+)\}/e", "''.strrev('\\1').''", "The {Quick} Brown {Fox}");
// We could use a Closure (callback function)
preg_replace_callback("/\{(\w+)\}/", function($m) { return strrev($m[1]); }, "The {Quick} Brown {Fox}");

Define an empty list

Assign the variable "list" to a list with no elements
php
$list = array();

Define a static list

Define the list [One, Two, Three, Four, Five]
php
$list = array("One", "Two", "Three", "Four", "Five");
$list = array();
$list[] = "One";
$list[] = "Two";
$list[] = "Three";
$list[] = "Four";
$list[] = "Five";
<?php
$list = new SplFixedArray(5);

$list[0] = "One";
$list[1] = "Two";
$list[2] = "Three";
$list[3] = "Four";
$list[4] = "Five";
?>

Join the elements of a list, separated by commas

Given the list [Apple, Banana, Carrot] produce "Apple, Banana, Carrot"
php
$string = implode(", ", $fruits);

Join the elements of a list, in correct english

Create a function join that takes a List and produces a string containing an english language concatenation of the list. It should work with the following examples:
join([Apple, Banana, Carrot]) = "Apple, Banana, and Carrot"
join([One, Two]) = "One and Two"
join([Lonely]) = "Lonely"
join([]) = ""
php
function ImplodeToEnglish($array) {
// sanity check
if (!$array || !count ($array))
return "";

// get last element
$last = array_pop($array);

// if it was the only element - return it
if (!count ($array))
return $last;

return implode(", ", $array)." and ".$last;
}
//example
ImplodeToEnglish(array("Apple", "Banana")); // returns: Apple and Banana

Produce the combinations from two lists

Given two lists, produce the list of tuples formed by taking the combinations from the individual lists. E.g. given the letters ["a", "b", "c"] and the numbers [4, 5], produce the list: [["a", 4], ["b", 4], ["c", 4], ["a", 5], ["b", 5], ["c", 5]]
php
foreach ($short as $s) {
foreach ($long as $l) {
$list[] = array($l, $s);
}
}

From a List Produce a List of Duplicate Entries

Taking a list:
["andrew", "bob", "chris", "bob"]

Write the code to produce a list of duplicates in the list:
["bob"]
php
$arr = array('andrew', 'bob', 'chris', 'bob', 'chris', 'john', 'mary', 'lucy');

function match($a, $b)
{
// This is a separate function so you could include checking
// with loose comparisons or lowercase both strings, etc.
return $a === $b;
}

$results = array();

sort($arr);

for($i = 0; $i < count($arr) - 1; $i++)
{
if (match($arr[$i], $arr[$i+1]))
{
$results[] = $arr[$i];
$i++;
}
}
print_r($results);
$arr = array('lucy', 'andrew', 'lucy', 'bob', 'chris', 'bob', 'chris', 'john', 'mary');

function match($a, $b)
{
// This is a separate function so you could include checking
// with loose comparisons or lowercase both strings, etc.
return $a === $b;
}

$results = array();

for($i = 0; $i < count($arr); $i++)
{
if (isset($results[$arr[$i]]))
{
$results[$arr[$i]]++;
}
else
{
$results[$arr[$i]] = 0;
}
}

$out = array();

foreach($results as $name => $count)
{
echo $name . ':' . $count . '<br />';
if ($count > 0)
{
$out[] = $name;
}
}

print_r($out);
<?php
$array = array("andrew", "bob", "chris", "bob");
$counts = array_count_values($array);

$duplicates = array_filter(
array_unique($array),
function($key) use ($counts) {
return $counts[$key] > 1;
}
);
?>

Fetch an element of a list by index

Given the list [One, Two, Three, Four, Five], fetch the third element ('Three')
php
$list = array("One", "Two", "Three", "Four", "Five");
$three = $list[2];

Fetch the last element of a list

Given the list [Red, Green, Blue], access the last element ('Blue')
php
$list = array("Red", "Green", "Blue");
$last = array_pop($list);

// Be aware of that $list only contains two elements now - not three
$list = array("Red", "Green", "Blue");
$last = $list[count($list)-1];

Find the common items in two lists

Given two lists, find the common items. E.g. given beans = ['broad', 'mung', 'black', 'red', 'white'] and colors = ['black', 'red', 'blue', 'green'], what are the bean varieties that are also color names?
php
$result = array_intersect($beans, $colors);
sort($result); // just to clean it up :)

Display the unique items in a list

Display the unique items in a list, e.g. given ages = [18, 16, 17, 18, 16, 19, 14, 17, 19, 18], display the unique elements, i.e. with duplicates removed.
php
$ages = array(18, 16, 17, 18, 16, 19, 14, 17, 19, 18);
$ages = array_unique($ages);
// be aware of that $ages[6] will print 14

Remove an element from a list by index

Given the list [Apple, Banana, Carrot], remove the first element to produce the list [Banana, Carrot]
php
$list = array("Apple", "Banana", "Carrot");
unset($list[0]);

// Be aware of that $list[0] isn't set. "Banana" is still $list[1]
$list = array("Apple", "Banana", "Carrot");
array_shift($list);

// Be aware of that $list[0] is set to "Banana"

Remove the last element of a list

php
$list = array("Apple", "Banana", "Carrot");
unset($list[count($list)-1]);

// Be aware of that
// $list[] = "Orange";
// will be $list[3] and not $list[2]
$list = array("Apple", "Banana", "Carrot");
array_pop($list);

Rotate a list

Given a list ["apple", "orange", "grapes", "bananas"], rotate it by removing the first item and placing it on the end to yield ["orange", "grapes", "bananas", "apple"]
php
$list = array("Apple", "Orange", "Grapes", "Banana");
$first = array_shift($list); //get and remove the first
array_push($list, $first); //prepend the $first to the array

Gather together corresponding elements from multiple lists

Given several lists, gather together the first element from every list, the second element from every list, and so on for all corresponding index values in the lists. E.g. for these three lists, first = ['Bruce', 'Tommy Lee', 'Bruce'], last = ['Willis', 'Jones', 'Lee'], years = [1955, 1946, 1940] the result should produce 3 actors. The middle actor should be Tommy Lee Jones.
php
for ($i = 0; $i < $count; $i++) {
$list[] = array($first[$i], $last[$i], $years[$i]);
}
$list = array_map(NULL, $first, $last, $years);

List Combinations

Given two source lists (or sets), generate a list (or set) of all the pairs derived by combining elements from the individual lists (sets). E.g. given suites = ['H', 'D', 'C', 'S'] and faces = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'], generate the deck of 52 cards, confirm the deck size and check it contains an expected card, say 'Ace of Hearts'.
php
foreach ($suites as $suite) {
foreach ($faces as $face) {
$cards[] = $suite.$face;
}
}
if (count($cards) == 52) {
echo "The deck have all 52 cards.\n";
}
if (in_array("HA", $cards)) {
echo "The deck contains 'Ace of Heart'\n";
} else {
echo "The deck doesn't contain 'Ace of Heart'\n";
}

Perform an operation on every item of a list

Perform an operation on every item of a list, e.g.
for the list ["ox", "cat", "deer", "whale"] calculate
the list of sizes of the strings, e.g. [2, 3, 4, 5]
php
$sizes = array_map('strlen', array('ox', 'cat', 'deer', 'whale'));

Split a list of things into numbers and non-numbers

Given a list that might contain e.g. a string, an integer, a float and a date,
split the list into numbers and non-numbers.
php
$now = new DateTime();
$things = array('hello', 25, 3.14, $now);
$numbers = array_filter($things, 'is_numeric');
$others = array();
foreach ($things as $thing) {
if (!in_array($thing, $numbers)) {
$others[] = $thing;
}
}

Define an empty map

php
$map = array();
$map = array("" => "");

Define an unmodifiable empty map

php
/* It's not possible to define an array as a constant
* Instead we can use the serialize-function */

$fruits = array("apple", "banana", "orange");
define("FRUITS", serialize($fruits));
echo FRUITS; // a:3:{i:0;s:5:"apple";i:1;s:6:"banana";i:2;s:6:"orange";}
$my_fruits = unserialize(FRUITS); // and normal array again

Define an initial map

Define the map {circle:1, triangle:3, square:4}
php
$map = array("circle" => 1, "triangle" => 3, "square" => 4);

Check if a key exists in a map

Given a map pets {joe:cat,mary:turtle,bill:canary} print "ok" if an pet exists for "mary"
php
if (array_key_exists("mary", $pets)) {
echo "ok";
}
if (isset($pets["mary"])) { // only works if $pets["mary"] can't be false or 0
echo "ok";
}

Retrieve a value from a map

Given a map pets {joe:cat,mary:turtle,bill:canary} print the pet for "joe" ("cat")
php
echo $pets["joe"];

Add an entry to a map

Given an empty pets map, add the mapping from "rob" to "dog"
php
$pets["rob"] = "dog";

Remove an entry from a map

Given a map pets {joe:cat,mary:turtle,bill:canary} remove the mapping for "bill" and print "canary"
php
$last = array_pop($pets); // removes last key and assign it to the variable
echo $last;
$last = $pets[count($pets)-1];
echo $last;
unset($last);
$bill = $pets["bill"];
echo $bill;
unset($bill);
print_r(array_pop($pets));

Create a histogram map from a list

Given the list [a,b,a,c,b,b], produce a map {a:2, b:3, c:1} which contains the count of each unique item in the list
php
$list = array("a","b","a","c","b","b");
$map = array_count_values($list);

Categorise a list

Given the list [one, two, three, four, five] produce a map {3:[one, two], 4:[four, five], 5:[three]} which sorts elements into map entries based on their length
php
foreach ($array as $m) {
$l = strlen($m);
$map[$l][] = $m;
}
arsort($map);

Perform an action if a condition is true (IF .. THEN)

Given a variable name, if the value is "Bob", display the string "Hello, Bob!". Perform no action if the name is not equal.
php
if($name == "Bob") {
echo "Hello, Bob!";
}

Perform different actions depending on a boolean condition (IF .. THEN .. ELSE)

Given a variable age, if the value is greater than 42 display "You are old", otherwise display "You are young"
php
if($age < 42) {
echo "You are young";
} else {
echo "You are old";
}
echo "You are " . (($age < 43) ? "young" : "old");

Perform different actions depending on several boolean conditions (IF .. THEN .. ELSIF .. ELSE)

php
echo "You are " . (($age > 84) ? "really ancient" : (($age > 30) ? "middle-aged" : "young"));
$response = "You are ";
if ($age > 84) {
$response .= "really ancient";
} else if ($age > 30) {
$response .= "middle-aged";
} else {
$response .= "young";
}
echo $response;

Replacing a conditional with many branches with a switch/case statement

Many languages support more compact forms of branching than just if ... then ... else such as switch or case or match. Use such a form to add an appropriate placing suffix to the numbers 1..40, e.g. 1st, 2nd, 3rd, 4th, ..., 11th, 12th, ... 39th, 40th
php
function suffix($n) {
switch ($n) {
case ($n % 100 >= 4) && ($n % 100 <= 20):
return 'th';
case $n % 10 == 1:
return 'st';
case $n % 10 == 2:
return 'nd';
case $n % 10 == 3:
return 'rd';
default:
return 'th';
}
}
for ($n=1; $n<=40; $n++) {
echo $n . suffix($n) ."\n";
}

Perform an action multiple times based on a boolean condition, checked before the first action (WHILE .. DO)

Starting with a variable x=1, Print the sequence "1,2,4,8,16,32,64,128," by doubling x and checking that x is less than 150.
php
$x = 1;
while($x < 150) {
echo "$x,";
$x *= 2;
}
$x = 0;
$c = pow(2, $x);
while($c < 150) {
echo "$c,";
$c = pow(2, $x++);
}

Perform an action multiple times based on a boolean condition, checked after the first action (DO .. WHILE)

Simulate rolling a die until you get a six. Produce random numbers, printing them until a six is rolled. An example output might be "4,2,1,2,6"
php
do {
$rand = rand(1,6);
echo $rand;
if ($rand != 6) echo ", ";
} while ($rand != 6);

Perform an action a fixed number of times (FOR)

Display the string "Hello" five times like "HelloHelloHelloHelloHello"
php
for($i = 0; $i < 5; $i++) {
echo "Hello";
}

Perform an action a fixed number of times with a counter

Display the string "10 .. 9 .. 8 .. 7 .. 6 .. 5 .. 4 .. 3 .. 2 .. 1 .. Liftoff!"
php
for($i = 10; $i > 0; $i--) {
echo $i." .. ";
}
echo "Liftoff!";

Read the contents of a file into a string

php
$file_contents = file_get_contents("file.txt");

Process a file one line at a time

Open the source file to your solution and print each line in the file, prefixed by the line number, like:
1> First line of file
2> Second line of file
3> Third line of file
php
$lines = file('file.txt');
foreach ($lines as $lnum => $line) {
echo $line_num."> ".$line; // you may want to add a <br />\n
}
<?php
$lines = new SplFileObject('file.txt');
foreach ($lines as $line) {
echo $line;
}
?>

Write a string to a file

php
/****
* For some (security)reason I couldn't
* submit this without adding a space to
* the functionnames. Please remove it :)
****/

if ($fh = f open("file.txt", 'w')) {
f write($fh, "Some text\n");
f close($fh);
}
<?php
file_put_contents('file.txt', 'a string');
?>

Append to a file

php
<?php
if ($fh = fopen("file.txt", 'a')) { // a == append
fwrite($fh, "Append some text\n");
fclose($fh);
}
?>
<?php
file_put_contents('file.txt', 'a string to append', FILE_APPEND);
?>

Process each file in a directory

php
if ($dh = opendir($dir)) { // if we have access
while (($file = readdir($dh)) !== false) { // as long as there is a file
echo "name: $file\n"; // echo its name
}
closedir($dh); // close the dir
}

Process each file in a directory recursively

php

if ($dir_handle = opendir($dir))
list_dir($dir_handle);

function list_dir($dh) {
// as long as we can read the dir
while (($file = readdir($dh)) !== false) {
// if it's a dir and it's not the current dir nor the above dir
if (is_dir($file) && $file != '.' && $file !='..') {
// open the dir, print it's name and all files inside
$handle = opendir($file);
echo $file."\n";
list_dir($handle);
// if it's a simple file
} else if ($file != '.' && $file !='..') {
// type it's name
echo $file."\n";
}
}
closedir($dir_handle); // close the dirs
}

Parse a date and time from a string

Given the string "2008-05-06 13:29", parse it as a date representing 6th March, 2008 1:29:00pm in the local time zone.
php
echo date("jS F, Y g:i:sa", strtotime("2008-05-06 13:29")); // small version

Display information about a date

Display the day of month, day of year, month name and day name of the day 8 days from now.
php
$eightdays = strtotime("+8 days");

$dayofmonth = date("d", $eightdays); // 3
$dayofyear = date("z", $eightdays); // 183
$monthname = date("F", $eightdays); // July
$dayname = date("l", $eightdays); // Saturday
$eightdays = time() + 1 * 60 * 60 * 24 * 8;

$dayofmonth = date("d", $eightdays); // 3
$dayofyear = date("z", $eightdays); // 183
$monthname = date("F", $eightdays); // July
$dayname = date("l", $eightdays); // Saturday

Display a date in different locales

Display a language/locale friendly version of New Year's Day for 2009 for several languages/locales. E.g. for languages English, French, German, Italian, Dutch the output might be something like:

Thursday, January 1, 2009
jeudi 1 janvier 2009
giovedì 1 gennaio 2009
Donnerstag, 1. Januar 2009
donderdag 1 januari 2009

(Indicate in comments where possible if any language specific or operating system configuration needs to be in place.)
php
/* Be aware of that you need to have the locales installed */
setlocale(LC_TIME, "en_US");
echo strftime("%A, %B %e, %Y%n"); // %n = \n in strftime()
setlocale(LC_TIME, "fr_FR"); // French
echo strftime("%A, %B %e, %Y%n");
setlocale(LC_TIME, "de_DE"); // German
echo strftime("%A, %B %e, %Y%n");
setlocale(LC_TIME, "it_IT"); // Italian
echo strftime("%A, %B %e, %Y%n");
setlocale(LC_TIME, "nl_NL", "nld_nld"); // Dutch; Unix and Windows
echo strftime("%A, %B %e, %Y%n");
$locales = array("en_US", "fr_FR", "de_DE", "nl_NL", "it_IT");
foreach ($locales as $locale) {
setlocale(LC_TIME, $locale);
echo strftime("%A, %B %d %Y%n");
}

Display the current date and time

Create a Date object representing the current date and time. Print it out.
If you can also do this without creating a Date object you can show that too.
php
echo date('r') . "\n";
$d = new DateTime();
echo $d->format('r') . "\n";
OOP

Define a class

Declare a class named Greeter that takes a string on creation and greets using this string if you call the "greet" method.
php
class Greeter {
private $whom;
public function __construct($whom) {
$this->whom = $whom;
}
public function greet() {
echo "Hello $this->whom.";
}
}
$g = new Greeter("Giacomo Girolamo");
$g->greet();

Instantiate object with mutable state

Reimplement the Greeter class so that the 'whom' property or data member remains private but is mutable, and is provided with getter and setter methods. Invoke the setter to change the greetee, invoke 'greet', then use the getter in displaying the line, "I have just greeted {whom}.".

For example, if the greetee is changed to 'Tommy' using the setter, the 'greet' method would display:

Hello, Tommy!

The getter would then be used to display the line:

I have just greeted Tommy.
php
class Greeter {
private $whom;
public function __construct($whom) {
$this->whom = $whom;
}
public function greet() {
echo "Hello $this->whom.\n";
}
public function getWhom() {
return $this->whom;
}
public function setWhom($whom) {
$this->whom = $whom;
}
}
$g = new Greeter("Giacomo Girolamo");
$g->greet();
$g->setWhom("Jean-Jaques");
$g->greet();
echo "I have just greeted " . $g->getWhom() . ".\n";

Implement Inheritance Heirarchy

Implement a Shape abstract class which will form the base of an inheritance hierarchy that models 2D geometric shapes. It will have:

* A non-mutable 'name' property or data member set by derived or descendant classes at construction time
* A 'area' method intended to be overridden by derived or descendant classes ( double precision floating point return value)
* A 'print' method (also for overriding) will display the shape's name, area, and all shape-specific values

Two derived or descendant classes will be created:
* Circle    -> Constructor requires a '
radius' argument, and a 'circumference' method to be implemented  
* Rectangle -> Constructor requires '
length' and 'breadth' arguments, and a 'perimeter' method to be implemented 

Instantiate an object of each class, and invoke each objects '
print' method to show relevant details.
php
<?php
abstract class Shape
{
protected $name;
abstract public function area ();
abstract public function _print ();
public function __construct ($name)
{
$this->name = $name;
}
}

class Circle extends Shape
{
protected $radius;
public function __construct ($radius)
{
parent::__construct('Circle');
$this->radius = $radius;
}
public function area ()
{
return pi() * $this->radius * $this->radius;
}
public function circumference ()
{
return 2 * pi() * $this->radius;
}
public function _print ()
{
print("I am a {$this->name} with ->\n");
print(" Radius: {$this->radius}\n");
print(" Area: {$this->area()}\n");
print(" Circumference {$this->circumference()}\n");
}
}

class Rectangle extends Shape
{
protected $length;
protected $breadth;
public function __construct ($length, $breadth)
{
parent::__construct('Rectangle');
$this->length = $length;
$this->breadth = $breadth;
}
public function area ()
{
return $this->length * $this->breadth;
}
public function perimeter ()
{
return (2 * $this->length) + (2 * $this->breadth);
}
public function _print ()
{
print("I am a {$this->name} with ->\n");
print(" Length, Width: {$this->length}, {$this->breadth}\n");
print(" Area: {$this->area()}\n");
print(" Perimeter: {$this->perimeter()}\n");
}
}

$shapes = array(new Circle(4.2) , new Rectangle(2.7, 3.1) , new Rectangle(6.2, 2.6) , new Circle(17.3));

foreach ($shapes as $shape) {
$shape->_print();
}

Implement and use an Interface

Create a Serializable interface consisting of 'save' and 'restore' methods, each of which:

* Accept a stream or handle or descriptor argument for the source or destination
* Save to destination or restore from source the properties or data members of the implementing class (restrict yourself to the primitive types 'int' and 'string')

Next, create a Person class which has 'name' and 'age' properties or data members and implements this interface. Instantiate a Person object, save it to a serial stream, and instantiate a new Person object by restoring it from the serial stream.
php
class Person implements Serializable {
private $name;
private $age;
public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
public function serialize() {
return serialize(array($this->name, $this->age));
}
public function unserialize($serialized) {
list($this->name, $this->age) = unserialize($serialized);
}
public function getData() {
return array($this->name, $this->age);
}
}

$obj = new Person('Gaylord Focker', 21);
file_put_contents('person.dump', serialize($obj));

$newobj = unserialize(file_get_contents('person.dump'));

var_dump($newobj->getData());

Check your language appears on the langref.org site

Your language name should appear within the HTML found at the http://langreg.org main page.
php
if (preg_match("/PHP/i", file_get_contents("http://langref.org/"))) {
echo "PHP appears on langref.org";
} else {
echo "PHP doesn't appear on langref.org";
}

Send an email

Use library functions, classes or objects to create a short email addressed to your own email address. The subject should be, "Greetings from langref.org", and the user should be prompted for the message body, and whether to cancel or proceed with sending the email.
php
/* This is a version without any prompt – use it for a website */
$to = "mail@domain.tld";
$subject = "Greetings from langref.org";
$body = "Hi,\n\nHow are you?";
$headers = "From: sender@domain.tld\n"; // you can comment this out and delete it from below
if (mail($to, $subject, $body, $headers)) {
echo "Success";
}

/****
* For some (security)reason I couldn't
* submit this without adding a space to
* the functionnames. Please remove it :)
* in this case, only "f write" and "f gets"
****/

$to = "mail@domain.tld";
f write(STDOUT, "Mail: ".$to."\n");
$subject = "Greetings from langref.org";
f write(STDOUT, "Subject: ".$subject."\n");
f write(STDOUT, "Please type the body. Use \\n for newlines: \n");
$body = trim(f gets(STDIN)); // we get input
if ($body == "") { // if empty input
$body = "Hi! How are you?";
f write(STDOUT, "Using standard body: ".$body."\n");
}
f write(STDOUT, "Would you like to send the mail? [y/n]: ");
if (trim(f gets(STDIN)) == "y") {
if (mail($to, $subject, $body)) {
f write(STDOUT, "Success\n");
} else { // fallback
f write(STDOUT, "Failed to mail\n");
}
} else { // fallback
f write(STDOUT, "I'm sorry :(\n");
}
XML

Process an XML document

Given the XML Document:

<shopping>
  <item name="bread" quantity="3" price="2.50"/>
  <item name="milk" quantity="2" price="3.50"/>
</shopping>

Print out the total cost of the items, e.g. $14.50
php
$xmlfile = simplexml_load_file('shop.xml');
$x = 0;
foreach ($xmlfile as $xml) {
// we have to declare that it's a float
$x = $x + ($xml['quantity'] * (float)$xml['price']);
}
echo $x;
$filename = "shop.xml";
if (($fp = fopen($filename, "r"))) {
while ($data = fread($fp, 4096)) {
$data = eregi_replace(">"."[[:space:]]+"."< ",">< ", $data);
if (!xml_parse($xmlparser, $data, feof($fp))) {
$reason = xml_error_string(xml_get_error_code($xmlparser));
$reason .= xml_get_current_line_number($xmlparser);
die($reason);
}
}
xml_parser_free($xmlparser);
echo $total; // Echo the total
}

create some XML programmatically

Given the following CSV:

bread,3,2.50
milk,2,3.50

Produce the equivalent information in XML, e.g.:

<shopping>
  <item name="bread" quantity="3" price="2.50" />
  <item name="milk" quantity="2" price="3.50" />
</shopping>
php
$xmllines = split("\n", $cvs);
foreach ($xmllines as $l) {
$xml[] = split(",", $l);
}
echo "<shopping>\n";
foreach ($xml as $x) {
echo "\t<item name=\"".$x[0]."\" quantity=\"".$x[1]."\" price=\"".$x[2]."\" />\n";
}
echo "</shopping>\n";

Find all Pythagorean triangles with length or height less than or equal to 20

Pythagorean triangles are right angle triangles whose sides comply with the following equation:

a * a + b * b = c * c

where c represents the length of the hypotenuse, and a and b represent the lengths of the other two sides. Find all such triangles where a, b and c are non-zero integers with a and b less than or equal to 20. Sort your results by the size of the hypotenuse. The expected answer is:

[3, 4, 5]
[6, 8, 10]
[5, 12, 13]
[9, 12, 15]
[8, 15, 17]
[12, 16, 20]
[15, 20, 25]
php
for ($x = 1; $x <= 20; $x++) {
for ($y = $x; $y <= 20; $y++) {
$z = hypot($x, $y); // or $z = sqrt($x*$x + $y*$y);
if (round($z) == $z) {
$array = array($x, $y, $z);
sort($array, SORT_NUMERIC);
$res[] = $array;
}
}
}

// calculate the total of the sides
foreach ($res as $a) {
$total[] = ($a[0] + $a[1] + $a[2]);
}
array_multisort($total, $res); // and sort them after the total
// result is in $res
Fun

produces a copy of its own source code

In computing, a quine is a computer program which produces a copy of its own source code as its only output.
php
// We make sure nothing else is outputted on the screen
ob_end_clean(); // Clean everything
die(highlight_file(__FILE__)); // Print and die

Create a multithreaded "Hello World"

Create a program which outputs the string "Hello World" to the console, multiple times, using separate threads or processes.

Example:

-Output-

Thread one says Hello World!
Thread two says Hello World!
Thread four says Hello World!
Thread three says Hello World!

-Notice that the threads can print in any order.
php
/*
The commented lines below can be used to verify new process are in use
*/
$text=array("one","two","three","four");
for ($i = 0; $i < 4; ++$i) {
$pid = pcntl_fork();
//$mypid=getmypid();
if (!$pid) {
//echo("Thread ".$text[$i]." says Hello World!(".$mypid.")\n");
echo("Thread ".$text[$i]." says Hello World!\n");
exit($i);
}
}