PHP
Implementation of programming language PHP
PHP Logo
Examples:
Factorial:
Example for versions PHP 5.2.4, PHP 5.3.2This example uses recursive factorial definition.
<?php
function factorial($n)
{
if ($n == 0) {
return 1;
}
return $n * factorial($n - 1);
}
for ($n = 0; $n <= 16; $n++) {
echo $n . "! = " . factorial($n) . "\n";
}
?>
Hello, World!:
Example for versions PHP 5.2.4, PHP 5.3.2<?php
echo "Hello, World!\n";
?>
Fibonacci numbers:
Example for versions PHP 5.2.4, PHP 5.3.2This example uses recursive definition of Fibonacci numbers.
<?php
function fibonacci($n)
{
if ($n < 3) {
return 1;
}
return fibonacci($n-1) + fibonacci($n-2);
}
for ($n = 1; $n <= 16; $n++) {
echo fibonacci($n) . ", ";
}
echo "...\n";
?>
Quadratic equation:
Example for versions PHP 5.3.2<?php
echo "A = ";
$A = (float) fgets(STDIN);
if ($A == 0) {
die("Not a quadratic equation\n");
}
echo "B = ";
$B = (float) fgets(STDIN);
echo "C = ";
$C = (float) fgets(STDIN);
$D = $B * $B - 4 * $A * $C;
if ($D == 0) {
echo "x = ", -$B / 2.0 / $A, "\n";
die();
}
if ($D > 0) {
echo "x1 = ", (-$B + sqrt($D)) / 2.0 / $A, "\n";
echo "x2 = ", (-$B - sqrt($D)) / 2.0 / $A, "\n";
} else {
echo "x1 = (", -$B / 2.0 / $A, ", ", sqrt(-$D) / 2.0 / $A, ")\n";
echo "x2 = (", -$B / 2.0 / $A, ", ", -sqrt(-$D) / 2.0 / $A, ")\n";
}
?>
CamelCase:
Example for versions PHP 5.3.2This example uses string functions and regular expressions. Function ucwords
converts first letter of each word to uppercase.
<?
$text = fgets(STDIN);
$text = str_replace(' ', '', ucwords(preg_replace('/[^a-z]/', ' ', strtolower($text))));
echo $text;
?>
Comments
]]>blog comments powered by Disqus
]]>